Course Content
C++ Data Types
C++ Data Types
Working With String
Append
As you saw in the previous chapter, we cannot add new characters to the end of a string using indexing. But C++ has a neat .append()
method for that. Here is the syntax:
Concatenate
Another way to do it is by using the +
operator.
It performs concatenation when applied to strings. Here is an example:
main
#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
#include <iostream> int main() { std::string str = "finity"; str = "code" + str + ".com"; std::cout << str << std::endl; }
Insert
You can also insert new text to a string at a desired position.
Here is the syntax:
Where pos
is an index, before which, new text is inserted.
Here is a gif of how insertion works:
Replace
You can also replace a part of a string with a different string.
This is achievable using the .replace()
method. Here is the syntax:
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 erase part of a string. Here is the syntax:
start
and n
parameters have the same meaning as in the .replace()
method.
In this chapter, you learned
Here is an example of using all of the methods.
main
#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; }
Thanks for your feedback!