Names, passwords, messages, file contents, DNA sequences: a huge share of real programs is about text. In C++ a piece of text is called a string.
C++ actually has two kinds of strings. The old one, inherited from C, is a plain array of characters ending with a special '\0' character. The modern one is the library class std::string, which manages its own memory, grows as needed and comes with dozens of useful operations. In this chapter we will focus on std::string, because it is what you should use in almost all new code, and then look at C-style strings and std::string_view so you can read older code and answer exam questions. We will build on the Arrays topic, since a C-style string is just a char array.
What is std::string?
std::stringis a standard library class (header<string>) that stores a sequence of characters in contiguous memory, keeps track of its own length, and automatically grows or shrinks as the text changes.
Unlike a char array, you never decide its size in advance, you can copy it with =, compare it with ==, and join two strings with +. Unlike Java's String, a C++ std::string is mutable: you can change its characters in place.
Creating and Joining Strings
#include <iostream>
#include <string>
int main() {
std::string first = "Asha"; // from a string literal
std::string last("Verma"); // constructor syntax
std::string stars(5, '*'); // 5 copies of '*'
std::string empty; // empty string ""
std::string full = first + " " + last; // concatenation
full += '!'; // append a char
full.append(" Welcome."); // append a string
std::cout << full << '\n';
std::cout << stars << '\n';
std::cout << "Length: " << full.length()
<< " (size() gives the same: " << full.size() << ")\n";
std::cout << std::boolalpha << "empty is empty? " << empty.empty() << '\n';
std::cout << "First char: " << full[0]
<< ", last char: " << full.back() << '\n';
full[0] = 'U'; // strings are mutable
std::cout << full << '\n';
}
Output:
Asha Verma! Welcome.
*****
Length: 20 (size() gives the same: 20)
empty is empty? true
First char: A, last char: .
Usha Verma! Welcome.
length()andsize()are exactly the same thing;size()matches the other standard containers. Both are O(1) because the string stores its length.empty()is the clean way to test for"".s[i]gives the character at indexi(indexes start at 0, as with arrays).front()andback()give the first and last character; calling them on an empty string is undefined behaviour.+creates a new string;+=andappendadd to the existing one, which is usually more efficient inside loops.
[] vs at(): Bounds Checking
Just like arrays, s[i] does no bounds checking: an index greater than s.size() is undefined behaviour. (Reading s[s.size()] is allowed and gives '\0'.) The member function at(i) checks the index and throws a std::out_of_range exception if it is invalid:
#include <iostream>
#include <string>
int main() {
std::string s = "hello";
std::cout << s[1] << ' ' << s.at(1) << '\n'; // both fine
std::cout << s.at(10) << '\n'; // throws std::out_of_range
}
Output in a terminal with GCC (the first line goes to standard output; the other two are printed to the error stream, and their exact text depends on the library):
e e
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 10) >= this->size() (which is 5)
Since we do not catch the exception, the program is terminated. We will learn to catch exceptions in the Exception Handling topic. Use [] in loops where you control the index; use at() when the index comes from outside (user input, a file) and you want a clean failure instead of silent memory corruption.
Comparing Strings
std::string supports ==, !=, <, >, <= and >=. They compare the contents, character by character, using the characters' numeric codes. This is called lexicographic (dictionary) order.
#include <iostream>
#include <string>
int main() {
std::string a = "apple", b = "banana", c = "Apple", d = "app";
std::cout << std::boolalpha;
std::cout << (a == "apple") << '\n'; // true: compares contents
std::cout << (a < b) << '\n'; // true: 'a' < 'b'
std::cout << (c < a) << '\n'; // true: 'A' (65) < 'a' (97)
std::cout << (d < a) << '\n'; // true: a prefix is smaller
std::cout << a.compare(b) << ' ' // negative, zero or positive
<< a.compare("apple") << ' '
<< b.compare(a) << '\n';
}
Output:
true
true
true
true
-1 0 1
How lexicographic comparison works:
Compare the strings from the left until two characters differ. The string with the smaller character is smaller (
"apple" < "banana"because'a' < 'b').If one string runs out first, the shorter one (the prefix) is smaller (
"app" < "apple").Uppercase letters (65 to 90 in ASCII) come before lowercase ones (97 to 122), so
"Zebra" < "apple"is true. For case-insensitive comparison, convert both strings to the same case first.
a.compare(b) returns a negative number, zero, or a positive number. The standard only promises the sign: GCC happened to print -1 and 1 above, but another library (or a different pair of strings) may give other values such as -98 or 2, so never test for exactly -1.
Reading Strings from Input
We met std::cin and std::getline in the Input & Output topic. With strings, two facts cause most beginner bugs:
std::cin >> sskips leading whitespace and then reads one word, stopping at the next space, tab or newline.std::getline(std::cin, s)reads a whole line, up to the newline. The newline is removed from the input and not stored ins.
Mixing the two causes a famous problem. Input:
21
Rahul Kumar
#include <iostream>
#include <string>
int main() {
int age;
std::string name;
std::cin >> age; // reads 21, leaves '\n' in the input
std::getline(std::cin, name); // reads up to that '\n' -> empty line!
std::cout << "age = " << age << ", name = [" << name << "]\n";
}
Output:
age = 21, name = []
The name is empty! std::cin >> age read 21 but left the newline after it in the input. getline then saw that newline immediately and returned an empty line. The fix is to throw away the leftover whitespace first, with std::ws (or std::cin.ignore(...)):
21
Rahul Kumar
Priya Sharma
#include <iostream>
#include <string>
int main() {
int age;
std::string first, name;
std::cin >> age;
std::getline(std::cin >> std::ws, name); // std::ws skips the leftover '\n'
std::cin >> first; // operator>> reads ONE word
std::cout << "age = " << age << ", name = [" << name << "]\n";
std::cout << "first = [" << first << "]\n";
}
Output:
age = 21, name = [Rahul Kumar]
first = [Priya]
Notice that std::cin >> first stopped at the space and took only "Priya". Use getline whenever the input may contain spaces.
Searching, Extracting and Modifying
#include <iostream>
#include <string>
int main() {
std::string s = "I love C++ and I love coding";
// searching
std::cout << "find(\"love\") = " << s.find("love") << '\n';
std::cout << "rfind(\"love\") = " << s.rfind("love") << '\n';
std::cout << "find(\"love\", 3) = " << s.find("love", 3) << '\n';
std::size_t pos = s.find("Java");
if (pos == std::string::npos) {
std::cout << "\"Java\" not found\n";
}
// extracting
std::cout << "substr(2, 4) = " << s.substr(2, 4) << '\n';
std::cout << "substr(15) = " << s.substr(15) << '\n';
// modifying
std::string t = s;
t.replace(t.find("C++"), 3, "Python"); // replace 3 chars at that position
std::cout << t << '\n';
t.insert(0, ">> ");
std::cout << t << '\n';
t.erase(0, 3); // remove 3 chars from index 0
std::cout << t << '\n';
// C++20 and C++23 helpers
std::cout << std::boolalpha
<< s.starts_with("I love") << ' ' // C++20
<< s.ends_with("coding") << ' ' // C++20
<< s.contains("C++") << '\n'; // C++23
}
Output:
find("love") = 2
rfind("love") = 17
find("love", 3) = 17
"Java" not found
substr(2, 4) = love
substr(15) = I love coding
I love Python and I love coding
>> I love Python and I love coding
I love Python and I love coding
true true true
Function | What it does | Note |
|---|---|---|
| Index of the first occurrence of | Returns |
| Index of the last occurrence | Also returns |
| First position of any of the given characters | Handy for finding separators |
| New string of at most | Without |
| Replaces | Lengths may differ |
| Inserts | Shifts the rest: O(n) |
| Removes | Shifts the rest: O(n) |
| Add / remove one character at the end |
|
| Makes the string empty | |
| Prefix / suffix test | C++20 |
| Substring or character test | C++23 |
Always check for npos
std::string::npos is the largest value of std::size_t (a huge unsigned number), used to mean "not found". A classic bug is using the result of find without checking it:
std::size_t pos = s.find("Java"); // npos: not found
std::string rest = s.substr(pos); // throws std::out_of_range
Also, store the result in std::size_t (or auto), not in int: converting npos to int gives -1 on common systems, which hides the mistake and invites signed/unsigned bugs. The standard does not say which search algorithm find uses; common implementations do a simple scan whose worst case is about O(n × m) for a text of length n and a pattern of length m. For huge texts, algorithms like KMP (or std::boyer_moore_searcher, C++17) are better.
Converting Between Numbers and Strings
#include <iostream>
#include <string>
int main() {
int roll = 42;
double cgpa = 8.75;
std::string label = "Roll " + std::to_string(roll); // number -> string
std::cout << label << '\n';
std::cout << std::to_string(cgpa) << '\n';
int n = std::stoi("2025"); // string -> int
double d = std::stod("3.14"); // string -> double
int partial = std::stoi(" 77 marks"); // skips leading spaces, stops at ' '
std::cout << n + 1 << ' ' << d * 2 << ' ' << partial << '\n';
std::cout << std::stoi("ff", nullptr, 16) << ' ' // base 16
<< std::stoi("1011", nullptr, 2) << '\n'; // base 2
}
Output:
Roll 42
8.750000
2026 6.28 77
255 11
std::to_string(C++11) turns a number into a string. For adoubleit uses six decimal places, likeprintf("%f"), which is why 8.75 became "8.750000". (C++26 changes this to the shortest form that reads back exactly; GCC 15 with-std=c++26already prints "8.75".)std::stoi,std::stol,std::stollandstd::stod(C++11) go the other way. They skip leading whitespace and convert as many characters as they can, so" 77 marks"gives 77.If no conversion is possible (for example
std::stoi("abc")), they throwstd::invalid_argument; if the number does not fit, they throwstd::out_of_range.The optional third argument is the base:
std::stoi("ff", nullptr, 16)is 255.
Working with Individual Characters
A std::string is a sequence of char, so the range-based for loop from the Arrays topic works directly. The character functions in <cctype> (isdigit, isalpha, isspace, toupper, tolower, ...) are handy here, with one subtlety explained below.
#include <cctype>
#include <iostream>
#include <string>
bool isPalindrome(const std::string& s) {
if (s.empty()) return true;
std::size_t i = 0, j = s.size() - 1;
while (i < j) {
if (s[i] != s[j]) return false;
++i;
--j;
}
return true;
}
int main() {
std::string text = "Hello World 2026";
int vowels = 0, digits = 0, spaces = 0;
for (char ch : text) {
unsigned char u = static_cast<unsigned char>(ch);
char lower = static_cast<char>(std::tolower(u));
if (lower == 'a' || lower == 'e' || lower == 'i' ||
lower == 'o' || lower == 'u') ++vowels;
else if (std::isdigit(u)) ++digits;
else if (std::isspace(u)) ++spaces;
}
std::cout << "vowels=" << vowels << " digits=" << digits
<< " spaces=" << spaces << '\n';
std::string upper = text;
for (char& ch : upper) {
ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
}
std::cout << upper << '\n';
std::string reversed(text.rbegin(), text.rend());
std::cout << reversed << '\n';
std::cout << std::boolalpha << isPalindrome("madam") << ' '
<< isPalindrome("hello") << ' ' << isPalindrome("") << '\n';
}
Output:
vowels=3 digits=4 spaces=2
HELLO WORLD 2026
6202 dlroW olleH
true false true
Why the
static_cast<unsigned char>? The<cctype>functions take anintthat must be eitherEOFor a value representable asunsigned char. On most systemscharis signed, so a non-ASCII character (like é in some encodings) is a negative number, and passing it directly is undefined behaviour. Casting tounsigned charfirst makes it safe.for (char& ch : upper)uses a reference so we can change the characters in place (more in the References topic).std::string reversed(text.rbegin(), text.rend());builds a new string by walking the original backwards using reverse iterators (see the Iterators topic).isPalindrometakesconst std::string&so the string is not copied. The two-index loop is the same idea as reversing an array: compare the ends, move inwards. The empty-string check matters becauses.size() - 1on an empty string would wrap around to a huge unsigned number.
C-Style Strings
Before std::string, text in C and C++ was stored as a null-terminated character array: the characters followed by a '\0' (the character with value 0) marking the end.
char name[] = "Ravi";
index: [0] [1] [2] [3] [4]
┌─────┬─────┬─────┬─────┬─────┐
│ 'R' │ 'a' │ 'v' │ 'i' │'\0' │
└─────┴─────┴─────┴─────┴─────┘
sizeof(name) = 5 strlen(name) = 4
The functions for C-strings live in <cstring>:
#include <cstring>
#include <iostream>
#include <string>
int main() {
char name[] = "Ravi"; // 5 chars: R a v i \0
std::cout << "sizeof = " << sizeof(name)
<< ", strlen = " << std::strlen(name) << '\n';
char buf[20];
std::strcpy(buf, name); // copy (buf must be big enough!)
std::strcat(buf, " Kumar"); // append
std::cout << buf << " (" << std::strlen(buf) << " chars)\n";
std::cout << (std::strcmp("abc", "abd") < 0) << '\n'; // 1: "abc" comes first
// converting between the two worlds
std::string s = buf; // C-string -> std::string
std::cout << s.size() << ' ' << s.c_str() << '\n'; // c_str(): std::string -> C-string
}
Output:
sizeof = 5, strlen = 4
Ravi Kumar (10 chars)
1
10 Ravi Kumar
Function | Purpose | Cost and danger |
|---|---|---|
| Number of characters before | O(n): it must scan for the terminator |
| Copy | No size check: overflow if |
| Append | No size check |
| Compare contents | Returns negative / 0 / positive |
Things that make C-strings risky:
The array must have room for the
'\0'.char s[4] = "Ravi";is an error in C++ (it is allowed in C, which silently drops the terminator).strcpyandstrcatnever check the destination size. Writing past the end is a buffer overflow, one of the most common security bugs in history.==on twochararrays compares addresses, not text, exactly like the array comparison problem in the Arrays topic. Usestrcmp.A string literal such as
"Ravi"has typeconst char[5]and must never be modified.
You still need C-strings to call C libraries and operating-system functions. s.c_str() gives a read-only, null-terminated version of a std::string for that purpose, and assigning a C-string to a std::string copies it. Remember that the result of c_str() becomes invalid as soon as the std::string is modified or destroyed.
Why "Hello" + " World" Does Not Compile
A string literal is not a std::string; it is a const char array. Two arrays cannot be added:
#include <string>
int main() {
std::string s = "Hello" + " World";
}
s10_nocompile_plus.cpp: In function ‘int main()’:
s10_nocompile_plus.cpp:4:29: error: invalid operands of types ‘const char [6]’ and ‘const char [7]’ to binary ‘operator+’
4 | std::string s = "Hello" + " World";
| ~~~~~~~ ^ ~~~~~~~~
| | |
| | const char [7]
| const char [6]
It works as soon as at least one side of each + is a std::string. Since C++14 the s suffix creates a std::string literal directly:
#include <iostream>
#include <string>
int main() {
using namespace std::string_literals; // enables the s suffix (C++14)
auto a = "Hello"; // a is const char* (a C-string)
auto b = "Hello"s; // b is std::string
std::string ok1 = std::string("Hello") + " World";
std::string ok2 = b + " World";
std::cout << ok1 << " | " << ok2 << " | " << a << '\n';
}
Output:
Hello World | Hello World | Hello
Note that auto a = "Hello"; gives a const char*, not a std::string. This surprises many people, and is another reason the s suffix is useful. Because + groups from left to right (x + y + z means (x + y) + z), s + "a" + "b" works but "a" + "b" + s does not.
std::string_view (C++17)
Passing const std::string& to a function avoids a copy, but if the caller passes a string literal, a temporary std::string must still be created. std::string_view (header <string_view>) is a lightweight, read-only window onto characters that live somewhere else: it stores only a pointer and a length.
#include <iostream>
#include <string>
#include <string_view>
// Accepts std::string, string literals and char arrays without copying.
std::size_t countChar(std::string_view text, char c) {
std::size_t count = 0;
for (char ch : text) {
if (ch == c) ++count;
}
return count;
}
int main() {
std::string s = "banana";
std::cout << countChar(s, 'a') << ' '
<< countChar("mississippi", 's') << '\n';
std::string_view sv = "Hello, World";
std::cout << sv.substr(7, 5) << '\n'; // a view, no new string made
sv.remove_prefix(7);
std::cout << sv << " (" << sv.size() << ")\n";
}
Output:
3 4
World
World (5)
substr on a string_view is O(1): it just makes a smaller window, no characters are copied. The big rule: a string_view does not own its characters. If the string it looks at is destroyed or changed, the view dangles, and using it is undefined behaviour:
std::string_view bad = std::string("temp"); // the temporary string dies at the ;
std::cout << bad; // undefined behaviour: dangling view
Use std::string_view for function parameters that only read text. Use std::string when you need to store or modify the text.
How std::string Manages Memory
A std::string keeps three things: a pointer to its characters, its size (characters in use) and its capacity (characters it can hold before it must allocate a larger buffer). When it runs out of room, it allocates a bigger buffer, copies the characters over and frees the old one. Watching the capacity with GCC's library:
#include <iostream>
#include <string>
int main() {
std::string s;
std::cout << "size " << s.size() << ", capacity " << s.capacity() << '\n';
for (int i = 0; i < 40; ++i) {
std::size_t before = s.capacity();
s += 'x';
if (s.capacity() != before) {
std::cout << "size " << s.size() << ", capacity " << s.capacity() << '\n';
}
}
}
Output (libstdc++; other libraries grow differently):
size 0, capacity 15
size 16, capacity 30
size 31, capacity 60
Two implementation details show up here. First, an empty string already holds 15 characters: short strings are stored inside the string object itself, with no heap allocation at all. This is called the small string optimisation (SSO); the limit is 15 characters in libstdc++ (GCC) and 22 in libc++ (Clang) on 64-bit systems. Second, the capacity roughly doubles each time, so appending one character at a time costs amortised O(1) per character. If you know the final size in advance, call s.reserve(n) to allocate once.
std::string vs C-Style String
Feature |
| C-style |
|---|---|---|
Size | Grows automatically | Fixed when declared |
Length |
|
|
Copy |
|
|
Join |
|
|
Compare |
|
|
Can contain | Yes | No, it marks the end |
Memory management | Automatic | Manual |
Use for | Almost all C++ code | C APIs, very low-level code |
Common Mistakes
Forgetting
#include <string>. It may compile by accident because<iostream>sometimes includes it, but that is not guaranteed.Using
getlineright aftercin >>and getting an empty line. Usestd::cin >> std::wsfirst.Not checking
findagainstnpos, or storing its result in anint.Writing
"a" + "b", which tries to add two arrays.Passing a plain
chartotoupper/isdigitwithout casting tounsigned char.Passing
std::stringby value to functions that only read it. Useconst std::string&orstd::string_view.Keeping a
string_vieworc_str()pointer after the original string has changed or died.Building a long string with repeated
s = s + x, which creates a new string every time. Uses += x.
Interview Questions
What is the difference between size() and length() of std::string?
None. They return the same value. length() exists for readability; size() exists for consistency with other containers.
What does sizeof return for char s[] = "GATE"; and what does strlen return?
sizeof(s) is 5 (four letters plus '\0'). strlen(s) is 4 (it does not count the terminator).
What does s.find("x") return when "x" is not present?
std::string::npos, which is the maximum value of std::size_t, i.e. static_cast<std::size_t>(-1).
What is the difference between s[i] and s.at(i)?
s[i] does no bounds check (an index above size() is undefined behaviour). s.at(i) checks the index and throws std::out_of_range if i >= size().
Is std::string mutable? How is that different from Java?
Yes, a std::string can be changed in place (s[0] = 'X', s += "..."). Java's String is immutable; changing it creates a new object, which is why Java has StringBuilder.
What is the small string optimisation?
An implementation technique where short strings are stored in a buffer inside the std::string object itself, avoiding a heap allocation. It is not required by the standard, but all major libraries do it (15 characters in libstdc++, 22 in libc++, on 64-bit).
Why is auto s = "hi"; not a std::string?
A string literal has type const char[3], and auto deduces const char* from it. Use std::string s = "hi"; or auto s = "hi"s; (C++14, with using namespace std::string_literals;).
When should a function take std::string_view instead of const std::string&?
When it only reads the text and does not need to store it or call functions that require a null-terminated string. string_view accepts literals and parts of strings without any copy. It is not guaranteed to be null-terminated, so do not pass sv.data() to C functions expecting a C-string.
In Simple Words
Use
std::stringfor text in C++. It knows its own length, grows automatically, and supports=,+and==on the contents. C-style strings arechararrays ending in'\0', and are mainly needed to talk to C code.
cin >>reads one word;getlinereads a line; usestd::wswhen mixing them.findreturnsnposwhen nothing is found; always check it.[]is unchecked,at()throws on a bad index."a" + "b"does not compile; one side must be astd::string.std::string_view(C++17) is a cheap read-only view, but it must not outlive the text it views.