In this C++ tutorial, you will learn how strings are represented using std::string, how to declare and initialize string variables, how to read string input, and how to perform commonly used string operations. The tutorial also provides a categorized list of C++ string tutorials for searching, checking, modifying, and converting strings.

What is a C++ String?

In C++, a string is commonly represented by an object of the std::string class provided by the standard library. A std::string stores a sequence of characters and provides functions for working with that sequence.

The std::string class is declared in the <string> header and belongs to the std namespace.

The following is an example for a string.

</>
Copy
"Hello World"

The string contains 11 characters: five characters in Hello, one space, and five characters in World. Text enclosed in double quotes, such as "Hello World", is a string literal in C++.

string itself is not a C++ keyword. The standard string type is std::string. If using namespace std; or using std::string; has been declared, the shorter name string can be used.

</>
Copy
string s = "Hello World";

How to Declare a String in C++

Use std::string followed by the variable name to declare a string. You can create an empty string or initialize it with a value.

</>
Copy
std::string variable_name = "text";

The following example declares three string variables in different ways.

</>
Copy
#include <iostream>
#include <string>

int main() {
    std::string firstName = "John";
    std::string message("Hello");
    std::string emptyString;

    std::cout << firstName << "\n";
    std::cout << message << "\n";
    std::cout << emptyString.length() << "\n";

    return 0;
}
John
Hello
0

C++ String Input with cin and getline()

C++ provides different ways to read text into a string. The extraction operator >> with std::cin reads characters until whitespace is encountered. Therefore, it is suitable when you need a single word.

</>
Copy
std::string name;
std::cin >> name;

To read an entire line containing spaces, use std::getline().

</>
Copy
std::string fullName;
std::getline(std::cin, fullName);

For example, if the input is John Smith, std::cin >> name reads only John, while std::getline(std::cin, fullName) can read John Smith as one string.

If you use std::getline() immediately after formatted input such as std::cin >> value, remember that a newline may remain in the input stream. Handle that newline before reading the next complete line when necessary.

Common C++ String Functions and Operations

The std::string class provides member functions and operators for common string operations. The following table summarizes frequently used operations.

OperationExamplePurpose
Lengths.length() or s.size()Returns the number of characters in the string.
Empty checks.empty()Checks whether the string contains no characters.
Character accesss[0]Accesses a character by its zero-based index.
Checked character accesss.at(0)Accesses a character and performs bounds checking.
Appends += "text"Adds characters to the end of a string.
Substrings.substr(0, 3)Creates a string from part of another string.
Finds.find("text")Searches for a character sequence.
Inserts.insert(...)Inserts characters at a specified position.
Replaces.replace(...)Replaces part of a string.
Erases.erase(...)Removes characters from a string.
Clears.clear()Removes all characters from the string.

length() and size() return the same number for a std::string. String indexes begin at 0, so the first character is available at index 0 when the string is not empty.

C++ String Example with Length, Access, Append, and Find

The following program demonstrates several basic std::string operations in one example.

</>
Copy
#include <iostream>
#include <string>

int main() {
    std::string text = "Hello";

    std::cout << "Length: " << text.length() << "\n";
    std::cout << "First character: " << text[0] << "\n";

    text += " World";
    std::cout << "Updated string: " << text << "\n";

    std::size_t position = text.find("World");
    if (position != std::string::npos) {
        std::cout << "World starts at index: " << position << "\n";
    }

    return 0;
}
Length: 5
First character: H
Updated string: Hello World
World starts at index: 6

When find() cannot locate the requested text, it returns std::string::npos. Comparing the result with std::string::npos is therefore a common way to test whether a substring exists.

Accessing Characters Safely in a C++ String

You can access characters with the subscript operator, such as s[index], or with s.at(index). Both use zero-based indexes.

The at() member function performs bounds checking and throws std::out_of_range when the supplied index is invalid. The subscript operator does not provide the same bounds-checking behavior, so make sure the index is within the string before using it.

C++ std::string vs C-Style Character Strings

C++ also supports C-style strings stored in character arrays. A C-style string uses a null character to mark the end of the text, while std::string is a standard-library class that provides its own size information and a collection of string operations.

</>
Copy
std::string cppString = "Hello";
char cStyleString[] = "Hello";

For most general-purpose C++ string handling, std::string provides a more direct interface for operations such as concatenation, searching, substring extraction, insertion, replacement, and comparison.

C++ String Tutorials

The following tutorials cover individual C++ string operations. They are grouped by the kind of task performed on the string or on individual characters.

C++ String Type Conversions

The following tutorials cover conversions between std::string and other commonly used C++ data representations, including integers and character arrays.

  1. C++ Convert string to integer
  2. C++ Convert integer to string
  3. C++ Convert string to char array
  4. C++ Convert char array to string

C++ Strings Summary

In this C++ Tutorial, we introduced std::string, string declaration and initialization, string input with std::cin and std::getline(), character access, and commonly used string operations. Use the categorized tutorials above for detailed examples of individual C++ string operations.