That requires a quite advanced compiler. Looking at Java, the process is:
- create a new string in some way.
- call String.intern() to create or retrieve
the interned string with the same contents.
If you do String si = (s+t).intern();
or String si = s.replace('a', 'b').intern();
it would take quite a compiler to prevent the creation of an intermediate string. You could have every function return an iterator over the characters that would end up in the string, iterate over that to check whether the string already is interned, and if not, iterate again to allocate a new string, but I think it would typically be cheaper to create it and let he young generation garbage collector collect it.