A string in C++ is a sequence of characters. Strings are used to store text, such as names, addresses, and messages.
To create a string in C++, you can use the std::string class. The std::string class is a header file called <string>.
For example, the following code creates a string named my_string and initializes it to the value "Hello, world!".
std::string my_string = "Hello, world!";
You can also use the "" and '' characters to create strings. However, it is generally considered best practice to use the std::string class when creating strings in C++.
String functions
The std::string class provides a variety of functions for working with strings. Some of the most common string functions include:
String examples
The following examples show how to use some of the most common string functions in C++:
// Create a string.
std::string my_string = "Hello, world!";
// Get the length of the string.
int length = my_string.length();
// Check if the string is empty.
bool empty = my_string.empty();
// Compare the string to another string.
int comparison = my_string.compare("Goodbye, world!");
// Find the first occurrence of a substring in the string.
int index = my_string.find("world");
// Extract a substring from the string.
std::string substring = my_string.substr(0, 5);
// Append one string to the end of another string.
my_string.append("!");
Conclusion
Strings are a powerful tool in C++. They can be used to store text, manipulate text, and perform other tasks. The std::string class provides a variety of functions for working with strings.