Skip to content

Module 4 · Pointers, Arrays, Strings and Structures — topic 3 of 4

Strings (std::string)

std::string manages text safely: construction, concatenation, comparison, searching, substrings, conversion to and from numbers, and string_view.

Beginner 15 min read·Lesson 15 of 40 in C++ Programming

Learning objectives

  • Create, compare and concatenate strings
  • Search and extract with find and substr
  • Convert between strings and numbers

Definition

std::string is a standard library class representing a mutable, dynamically sized sequence of characters that manages its own memory and supports value semantics.

Introduction

C strings require you to manage buffers and terminators. std::string does that for you: it grows as needed, can be compared with ==, joined with + and copied with =.

Why it matters

Text processing — names, commands, file lines — appears in every project; std::string removes buffer overflows.

String manipulation questions (palindromes, reversal, counting) are interview staples.

Detailed explanation

Construction: std::string s = "hello";, std::string line(5, '-');. Length: s.size() (or length()).

Operators: + and += concatenate; ==, < compare lexicographically; s[i] accesses a character (unchecked), s.at(i) with a check.

s.find(t) returns the index of the first match or std::string::npos if absent; s.substr(pos, len) extracts a part; s.replace, s.erase, s.insert modify in place.

Numbers: std::to_string(42); std::stoi("42"), std::stod("3.5") (these throw std::invalid_argument on bad input).

std::string_view (C++17) is a lightweight, non-owning view of characters — ideal for read-only parameters, but it must not outlive the string it views.

Syntax

C++
std::string name = "Ada";
name += " Lovelace";
auto pos = name.find(' ');
std::string first = name.substr(0, pos);
int n = std::stoi("123");
std::string t = std::to_string(3.5);
  • Include <string>.
  • Compare find results with std::string::npos.
  • c_str() gives a const char* for C APIs.

Code examples

Building and comparing

C++
#include <iostream>
#include <string>
int main() {
std::string a = "apple", b = "banana";
std::string both = a + " & " + b;
std::cout << both << " (" << both.size() << ")\n";
std::cout << (a < b) << ' ' << (a == "apple") << '\n';
return 0;
}
Output
apple & banana (14)
1 1

find and substr

C++
#include <iostream>
#include <string>
int main() {
std::string email = "asha.rao@kenholt.in";
auto at = email.find('@');
std::cout << email.substr(0, at) << '\n' << email.substr(at + 1) << '\n';
std::cout << (email.find("gmail") == std::string::npos ? "not gmail" : "gmail") << '\n';
return 0;
}
Output
asha.rao
kenholt.in
not gmail

More examples

Word processing

C++
#include <algorithm>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
bool is_palindrome(const std::string& s) {
std::string clean;
for (char c : s)
if (std::isalnum(static_cast<unsigned char>(c))) clean += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
return std::equal(clean.begin(), clean.begin() + clean.size() / 2, clean.rbegin());
}
int main() {
std::string sentence = "never odd or even";
std::istringstream words(sentence);
std::string w, longest;
int count = 0;
while (words >> w) {
++count;
if (w.size() > longest.size()) longest = w;
}
std::cout << count << " words, longest '" << longest << "'\n";
std::cout << "palindrome: " << std::boolalpha << is_palindrome(sentence) << '\n';
std::cout << "total: " << std::stoi("40") + std::stoi("2") << '\n';
return 0;
}
Output
4 words, longest 'never'
palindrome: true
total: 42

Step-by-step explanation

  • std::istringstream lets you read words from a string with >>.
  • The longest word is tracked by comparing sizes (ties keep the first).
  • is_palindrome keeps only letters and digits, lower-cased.
  • std::equal compares the first half with the reversed sequence.

Expected output

Running “Word processing” prints exactly:

TextOutput
4 words, longest 'never'
palindrome: true
total: 42

Practical applications

  • Parsers and command interpreters split strings into tokens.
  • Web back ends build JSON and HTML as strings.
  • Validation code searches for '@' and domains in emails.

Best practices

  • Use std::string for owned text and string_view for read-only parameters.
  • Check npos after every find.
  • Handle exceptions from stoi/stod when parsing user input.

Common mistakes

Comparing find with -1 or 0

Avoid

if (s.find("x") > 0) { /* found? */ }

Prefer

if (s.find("x") != std::string::npos) { /* found */ }

find returns an unsigned position; not found is npos, and a match at index 0 is still found.

Dangling string_view

Avoid

std::string_view v = std::string("temp");

Prefer

std::string owner = "temp";
std::string_view v = owner;

The temporary string is destroyed at the end of the statement, leaving the view pointing to freed memory.

Important notes

  • Short strings are usually stored inside the object without heap allocation (small-string optimisation).
  • <cctype> functions need unsigned char arguments to avoid undefined behaviour with negative chars.

Key takeaways

  • std::string supports +, ==, <, find, substr.
  • Not found is std::string::npos.
  • Convert with to_string and stoi/stod.

Try it yourself

  1. 1
    Count the vowels in a line read with getline.
  2. 2
    Replace every occurrence of a word in a sentence using find and replace in a loop.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

7 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat does `s.find("x")` return when "x" is not in s?
  • BeginnerWhat is printed?
Practise this topic