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.
"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.
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.
std::string variable_name = "text";
The following example declares three string variables in different ways.
#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.
std::string name;
std::cin >> name;
To read an entire line containing spaces, use std::getline().
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.
| Operation | Example | Purpose |
|---|---|---|
| Length | s.length() or s.size() | Returns the number of characters in the string. |
| Empty check | s.empty() | Checks whether the string contains no characters. |
| Character access | s[0] | Accesses a character by its zero-based index. |
| Checked character access | s.at(0) | Accesses a character and performs bounds checking. |
| Append | s += "text" | Adds characters to the end of a string. |
| Substring | s.substr(0, 3) | Creates a string from part of another string. |
| Find | s.find("text") | Searches for a character sequence. |
| Insert | s.insert(...) | Inserts characters at a specified position. |
| Replace | s.replace(...) | Replaces part of a string. |
| Erase | s.erase(...) | Removes characters from a string. |
| Clear | s.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.
#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.
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 Basics
C++ String Search and Character Access
- C++ Substring
- C++ String – Get character at specific index
- C++ String – Get first character
- C++ String – Get last character
- C++ String – Get first n characters
- C++ String – Get last n characters
- C++ String – Find index of substring
- C++ String – Iterate over characters
- C++ String – Print unique characters
C++ String Checks and Comparisons
- C++ Check if string is empty
- C++ Check if strings are equal
- C++ Check if string contains specific substring
- C++ Check if string contains specific character
- C++ Check if string contains only digits
- C++ Check if string contains only spaces
- C++ Check if string contains only certain character
- C++ Check if string starts with specific prefix
- C++ Check if string ends with specific suffix
- C++ Check if string is number
- C++ String comparison
C++ String Modification Operations
The following tutorials cover operations that change part or all of a string, including appending, concatenating, replacing, reversing, and changing letter case.
- C++ Append string
- C++ Concatenate strings
- C++ String reverse
- C++ String replace
- C++ Swap strings
- C++ Convert string to uppercase
- C++ Convert string to lowercase
- C++ Repeat string N times
C++ Character-Level String Manipulations
- C++ String – Append character at the end
- C++ String – Append character at beginning
- C++ String – Insert character at specific index
- C++ String – Remove first character
- C++ String – Remove last character
- C++ String – Replace specific character with another
- C++ String – Remove all occurrences of a specific character
C++ String Type Conversions
The following tutorials cover conversions between std::string and other commonly used C++ data representations, including integers and character arrays.
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.
TutorialKart.com