C++ Strings

C++ Strings

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.

Creating Strings

You define a string variable like this:

Example

#include <iostream>
#include <string>
using namespace std;

int main() { string greeting = "Hello C++"; cout << greeting; return 0; }

String Concatenation

You can join strings together using the + operator. This process is called concatenation.

Example

string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName; // Outputs John Doe

String Length

To find the length of a string, you can use the length() or size() function:

Example

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.


Exercise

?

Which operator is used to join (concatenate) two strings together in C++?