Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Working With String | Text Data Type
C++ Data Types
course content

Зміст курсу

C++ Data Types

C++ Data Types

1. Introduction
2. Numerical Data Types
3. Text Data Type
4. Other Data Types and Concepts

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:

cpp

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.

cpp

main

12345678
#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.

cpp

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; }

Все було зрозуміло?

Секція 3. Розділ 4
We're sorry to hear that something went wrong. What happened?
some-alt