Search⌘ K
AI Features

Mutable and Immutable Strings

Explore the concepts of mutable and immutable strings in C++. Understand how std::string allows in-place modification of characters and why this matters for string algorithm design and performance. Learn the differences between mutable strings and immutable types such as const strings and literals, and discover how to safely share or copy string data in your programs.

By this point, you know that individual characters in strings can be accessed and traversed, and that the length of a string can be determined using the same ideas that apply to arrays. That structural similarity makes strings feel familiar. Now we turn to an equally important question: what happens when you try to modify a string? Can you change a character in place the same way you change an array element? The answer is yes for std::string, and understanding why (and what that implies) directly affects how string algorithms are designed and how their performance is analyzed.

Modifying a string in C++

Consider a simple array of integers. Changing the first element is a straightforward operation in which the value at that position is simply overwritten.

C++ 17
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
std::cout << "Before updating: ";
for (int i = 0; i < 5; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
// Update first element
arr[0] = 99;
std::cout << "After updating: ";
for (int i = 0; i < 5; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}

The same operation works identically on a std::string.

C++ 17
#include <iostream>
#include <string>
int main() {
std::string s = "hello";
std::cout << "Before modification: " << s << std::endl;
s[0] = 'H';
std::cout << "After modification: " << s << std::endl; // Hello
return 0;
}

A character in a std::string can be replaced directly using the subscript operator, just like an element in an array. This is because std::string in C++ is a mutable ...