A string is a collection of characters used to store text. In C++, to use strings, you must include an additional header file in the source code, the <string> library.
You define a string variable like this:
#include <iostream> #include <string> using namespace std;int main() { string greeting = "Hello C++"; cout << greeting; return 0; }
You can join strings together using the + operator. This process is called concatenation.
string firstName = "John "; string lastName = "Doe"; string fullName = firstName + lastName; cout << fullName; // Outputs John Doe
To find the length of a string, you can use the length() or size() function:
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; cout << "The length of the txt string is: " << txt.length();
Strings are widely used for working with user text, file contents, and more.
Which operator is used to join (concatenate) two strings together in C++?