String immutability and StringBuilder

A string can never be changed after it is created. "Modifying" one always builds a new string.

Time s += x is O(n)Space a new string each timeCode C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

s += "!" allocates a new string holding the old characters plus the new one, then points s at it. The old string is untouched, which is why t still sees "Hi".

Code

string s = "Hi";
string t = s;
s += "!";               // builds a NEW string
Console.WriteLine(t);   // still "Hi"

var sb = new StringBuilder("Hi");
sb.Append("!");         // changes the same buffer
public class Main {
    public static void main(String[] args) {
        String s = "Hi";
        String t = s;
        s += "!";               // builds a NEW string
        System.out.println(t);  // still "Hi"

        StringBuilder sb = new StringBuilder("Hi");
        sb.append("!");         // changes the same buffer
    }
}
int main() {
    string s = "Hi";
    string t = s;           // std::string copies the characters
    s += "!";               // changes s in place; t is a separate copy
    cout << t << "\n";      // still "Hi"

    ostringstream sb("Hi", ios::ate);
    sb << "!";              // appends to the same buffer
}
s = "Hi"
t = s
s += "!"  # builds a NEW string
print(t)  # still "Hi"

parts = ["Hi"]  # no StringBuilder: collect pieces in a list
parts.append("!")  # changes the same list; "".join(parts) makes the string

Tips

In the .NET library

Use StringBuilder for loops, string.Join or string.Concat for collections, and interpolation ($"...") for a fixed handful of parts.