Common String Methods
Append
We saw that adding new characters to the end of a string using indexing is not possible. However, there is a convenient .append()
method for this purpose.
append
1str.append("added part");
Concatenate
Another way to do it is by using the +
operator. It performs concatenation when applied to strings.
main
12345678#include <iostream> int main() { std::string str = "Code"; str = str + "finity"; // or str += "finity" std::cout << str << std::endl; }
It also allows adding text to the beginning or to both ends, which .append()
is incapable of.
main
12345678#include <iostream> int main() { std::string str = "finity"; str = "code" + str + ".com"; std::cout << str << std::endl; }
Insert
You can insert new text into a string at a specific position using the .insert()
method.
insert
1str.insert(pos, "text to add");
The position, specified by the pos
parameter, determines where the new text will be added.
The new text is inserted before the character currently at the given position. This method is useful for dynamically modifying strings without creating new ones.
Replace
You can also replace a part of a string with a different string. This is achievable using the .replace()
method.
replace
1str.replace(start, n, "new text");
Here start
means the index of the first element to replace, and n
stands for the length of a part to replace.
The following is a gif of how .replace()
works.
Erase
You can also remove a portion of a string using the .erase()
method. This is useful when you need to delete specific characters or substrings from a string.
erase
1str.erase(start, n);
If the n
parameter matches or exceeds the remaining length of the string from start
, all characters from start
onward will be erased.
The start
and n
parameters work similarly to those in the .replace()
method, providing flexibility to modify the string as needed.
main
123456789101112131415161718192021#include <iostream> int main() { std::string str = "finity"; str.append(".com"); // finity to finity.com std::cout << str << std::endl; str = "in" + str; // finity.com to infinity.com std::cout << str << std::endl; str.insert(2, "de"); // infinity.com to indefinity.com std::cout << str << std::endl; str.replace(0, 2, "co"); // indefinity.com to codefinity.com std::cout << str << std::endl; str.erase(10, 4); // codefinity.com to codefinity std::cout << str << std::endl; }
Tak for dine kommentarer!
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat