LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 5 of 27

std::string

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

std::string · Study material

std::string in C++ is the standard class for text. Unlike a C character array, a std::string knows its length, grows automatically, can be copied, compared with == and joined with +, and frees its memory by itself. It comes with dozens of member functions – find, substr, replace, insert, erase – plus conversions such as std::stoi and std::to_string, the lightweight std::string_view, and C++20/23 helpers like starts_with and contains. String manipulation is the single most common category of coding interview questions. This page covers it all with programs you can run, followed by 60 practice questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.

On this page

  • std::string vs C-style strings; creating and concatenating
  • Accessing characters, length, iterating and changing case
  • find, rfind, npos, substr, replace, insert, erase, append
  • Comparing strings and converting between strings and numbers
  • Splitting and joining, std::string_view, C++20/23 functions, c_str()

std::string vs C-style strings

A C string is a char array ending in '\0'; you must manage its size, and =, + and == do not work on it. std::string (in <string>) stores its characters in managed memory and makes text behave like a normal value.

TaskC stringstd::string
Lengthstrlen(s) – O(n)s.size() – O(1)
Copystrcpy(d, s) (buffer must fit)d = s
Joinstrcat(d, s)d + s, d += s
Comparestrcmp(a, b) == 0a == b, a < b
Growmanual reallocationautomatic

Creating and concatenating strings

Strings can be created from literals, repeated characters, or parts of other strings. + joins strings when at least one operand is a std::string – "a" + "b" on two literals does not compile. += appends in place and is the efficient way to build text in a loop.

#include <iostream>
#include <string>

int main() {
    std::string empty;                    // ""
    std::string city = "Mumbai";          // from a string literal
    std::string stars(5, '*');            // "*****"
    std::string part(city, 0, 3);         // "Mum" – copy of a substring
    std::string copy = city;              // independent copy

    std::string greeting = "Hello, " + city + "!";   // + works when one side is a std::string
    greeting += " Welcome";                          // append
    copy[0] = 'm';                                   // changing the copy leaves city alone

    std::cout << '[' << empty << "] " << stars << ' ' << part << ' ' << copy << ' ' << city << '\n';
    std::cout << greeting << " (" << greeting.size() << " characters)\n";
    return 0;
}

Output

[] ***** Mum mumbai Mumbai
Hello, Mumbai! Welcome (22 characters)

Accessing characters and iterating

s[i] accesses a character without checking; s.at(i) throws std::out_of_range for a bad index. front()/back() give the first and last characters, size() and length() are the same thing. Use a range-for loop with char& to modify every character, and pass characters to <cctype> functions as unsigned char.

#include <cctype>
#include <iostream>
#include <string>

int main() {
    std::string s = "LearnFrenzy";
    std::cout << s[0] << s.at(5) << s.front() << s.back() << ' ' << s.length() << ' ' << s.empty() << '\n';

    for (char& c : s)                                   // reference: modify each character
        c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
    std::cout << s << '\n';

    int vowels = 0;
    for (char c : s)                                    // copy: just read
        if (std::string("AEIOU").find(c) != std::string::npos) ++vowels;
    for (std::size_t i = 0; i < s.size(); i += 2)       // index when position matters
        std::cout << s[i];
    std::cout << ' ' << vowels << " vowels\n";
    return 0;
}

Output

LFLy 11 0
LEARNFRENZY
LANRNY 3 vowels

Searching: find, rfind and npos

find returns the index of the first match and rfind of the last; when nothing is found they return std::string::npos – the largest size_t value – so always compare with npos, never with −1 or 0. find_first_of / find_last_of search for any of a set of characters, find_first_not_of for the first character not in a set. substr(pos, len) copies a part, and replace(pos, len, text) overwrites one.

#include <iostream>
#include <string>

int main() {
    std::string path = "/home/asha/projects/report.final.pdf";
    std::size_t slash = path.rfind('/');                   // last '/'
    std::size_t dot = path.rfind('.');                     // last '.'
    std::string file = path.substr(slash + 1);             // from position to the end
    std::string ext = path.substr(dot + 1);
    std::string folder = path.substr(0, slash);            // (position, length)
    std::cout << file << " | " << ext << " | " << folder << '\n';

    std::cout << path.find("asha") << ' ' << path.find('x') << ' '
              << (path.find('x') == std::string::npos) << '\n';   // npos = "not found"

    std::string msg = "I like Java. Java is fun.";
    for (std::size_t pos = 0; (pos = msg.find("Java", pos)) != std::string::npos; pos += 3)
        msg.replace(pos, 4, "C++");                        // replace every occurrence
    std::cout << msg << '\n';
    return 0;
}

Output

report.final.pdf | pdf | /home/asha/projects
6 18446744073709551615 1
I like C++. C++ is fun.

Modifying: insert, erase, append, replace

FunctionEffect
s.append(t) / s += t / s.push_back(c)add at the end
s.insert(pos, t)insert text before index pos
s.erase(pos, n) / s.erase(pos)remove n characters / everything from pos
s.replace(pos, n, t)replace n characters with t
s.pop_back() / s.clear()remove last character / everything
s.resize(n, c)truncate or pad with c
#include <iostream>
#include <string>

int main() {
    std::string s = "Hello World";
    s.insert(5, ",");                 // "Hello, World"
    s.append("!!");                   // "Hello, World!!"
    s.erase(s.size() - 1);            // remove from position to the end → one '!'
    s.push_back('?');
    s.pop_back();
    std::cout << s << '\n';

    s.erase(0, 7);                    // (position, count) → "World!"
    s.replace(0, 5, "C++");           // → "C++!"
    s.insert(s.begin(), '>');         // iterator version
    std::cout << s << ' ' << s.size() << '\n';
    s.clear();
    std::cout << '[' << s << "] " << s.empty() << '\n';
    return 0;
}

Output

Hello, World!
>C++! 5
[] 1

Comparing strings

==, !=, <, > compare character by character using character codes (lexicographic order). Uppercase letters (65–90) come before lowercase (97–122), and "10" < "9" is true because '1' < '9'. compare returns a negative number, zero or a positive number.

#include <iostream>
#include <string>

int main() {
    std::string a = "apple", b = "apricot", c = "Apple";
    std::cout << (a < b) << (a == "apple") << (c < a) << ("10" < std::string("9")) << '\n';
    std::cout << (a.compare(b) < 0) << ' ' << a.compare("apple") << '\n';   // <0, 0, >0
    return 0;
}

Output

1111
1 0

Converting between strings and numbers

std::to_string(x) turns a number into text. std::stoi, stol, stoll, stod parse a number from the start of a string (skipping leading spaces), optionally report how many characters were used, accept a base, and throw std::invalid_argument or std::out_of_range on failure. std::from_chars (C++17, <charconv>) is the fastest, locale-independent option and reports errors without exceptions.

#include <charconv>
#include <iostream>
#include <string>

int main() {
    std::string n = std::to_string(42) + "/" + std::to_string(7.5);   // number → string
    std::cout << n << '\n';

    int a = std::stoi("123");                        // string → int
    double d = std::stod("3.75e2");                  // string → double
    std::size_t used = 0;
    int b = std::stoi("250kg", &used);               // stops at the first non-digit
    int hex = std::stoi("ff", nullptr, 16);
    std::cout << a + 1 << ' ' << d << ' ' << b << " (used " << used << ") " << hex << '\n';

    std::string text = "9876";
    int value = 0;
    auto [ptr, ec] = std::from_chars(text.data(), text.data() + text.size(), value);   // fast, no exceptions
    std::cout << value << ' ' << (ec == std::errc{}) << '\n';
    return 0;
}

Output

42/7.500000
124 375 250 (used 3) 255
9876 1

Splitting and joining

C++ has no built-in split, but std::getline with a delimiter on an std::istringstream splits on a character (keeping empty fields), and >> splits on any whitespace. Joining is a simple loop with +=.

#include <iostream>
#include <sstream>
#include <string>
#include <vector>

std::vector<std::string> split(const std::string& s, char delim) {
    std::vector<std::string> parts;
    std::istringstream in(s);
    std::string item;
    while (std::getline(in, item, delim)) parts.push_back(item);
    return parts;
}

std::string join(const std::vector<std::string>& parts, const std::string& sep) {
    std::string out;
    for (std::size_t i = 0; i < parts.size(); ++i) {
        if (i) out += sep;
        out += parts[i];
    }
    return out;
}

int main() {
    auto fields = split("Asha,21,Pune,B.Tech", ',');
    std::cout << fields.size() << " fields, third = " << fields[2] << '\n';
    std::cout << join(fields, " | ") << '\n';

    std::istringstream words("  split   on   any   whitespace ");
    std::string w;
    int count = 0;
    while (words >> w) ++count;
    std::cout << count << " words\n";
    return 0;
}

Output

4 fields, third = Pune
Asha | 21 | Pune | B.Tech
4 words

std::string_view

std::string_view (C++17) is a non-owning, read-only view: a pointer and a length. Passing std::string_view instead of const std::string& accepts literals and strings without creating a temporary string, and substr on a view costs nothing. The rule: the viewed characters must outlive the view – never return a view of a local string.

#include <iostream>
#include <string>
#include <string_view>

// string_view: a read-only window onto characters owned by someone else – no copy
std::string_view file_extension(std::string_view name) {
    auto dot = name.rfind('.');
    return dot == std::string_view::npos ? std::string_view{} : name.substr(dot + 1);
}

int main() {
    std::string file = "notes.backup.txt";
    std::cout << file_extension(file) << ' ' << file_extension("archive.tar.gz") << ' '
              << '[' << file_extension("README") << "]\n";

    std::string_view sv = "  trimmed  ";
    sv.remove_prefix(sv.find_first_not_of(' '));
    sv.remove_suffix(sv.size() - sv.find_last_not_of(' ') - 1);
    std::cout << '[' << sv << "] " << sv.size() << '\n';
    return 0;
}

Output

txt gz []
[trimmed] 7

Modern helpers: starts_with, ends_with, contains, literals

C++20 added starts_with and ends_with; C++23 added contains. The "text"s literal (from std::string_literals) creates a std::string directly. Because a string is a container of chars, every algorithm works on it: std::reverse, std::sort, std::count, std::transform.

#include <algorithm>
#include <iostream>
#include <string>

using namespace std::string_literals;

int main() {
    std::string url = "https://learnfrenzy.com/programming";
    std::cout << url.starts_with("https") << url.ends_with(".com") << url.contains("frenzy") << '\n';   // C++20 / C++23

    auto s = "C++"s + "23";                         // "..."s is a std::string literal
    std::cout << s << ' ' << s.size() << '\n';

    std::string word = "programming";
    std::cout << std::count(word.begin(), word.end(), 'm') << ' ';
    std::reverse(word.begin(), word.end());
    std::cout << word << ' ';
    std::sort(word.begin(), word.end());
    word.erase(std::unique(word.begin(), word.end()), word.end());
    std::cout << word << '\n';
    return 0;
}

Output

101
C++23 5
2 gnimmargorp agimnopr

Working with C APIs: c_str() and data()

s.c_str() returns a const char* to a null-terminated copy-free buffer for functions such as std::strlen, printf("%s") or fopen. The pointer stays valid only until the string is modified or destroyed.

#include <cstdio>
#include <cstring>
#include <string>

std::string name = "report.txt";
std::size_t n = std::strlen(name.c_str());       // 10
std::printf("%s has %zu chars\n", name.c_str(), name.size());
FILE* f = std::fopen(name.c_str(), "r");          // C API needs const char*

Common mistakes

  • "a" + "b" adds two pointers and does not compile – make one side a std::string.
  • Comparing find() with -1 or 0 – compare with std::string::npos.
  • s + 1 where you meant s + "1"; s += 65 appends 'A'.
  • Using == on C strings compares addresses – use std::string or strcmp.
  • Returning a string_view of a local string – it dangles.
  • Calling toupper on a plain char with a negative value is undefined – cast to unsigned char.
  • stoi on bad input throws – catch std::invalid_argument, or use from_chars.

Key points to remember

  • std::string manages its own memory and supports =, +, += and comparisons.
  • find/rfind return npos when there is no match.
  • substr(pos, len) copies; replace, insert and erase modify in place.
  • to_string, stoi/stod and from_chars convert between text and numbers.
  • Use string_view for read-only parameters; keep its data alive.
  • Strings work with all standard algorithms.

Frequently asked questions

What is the difference between size() and length()?

None – both return the number of characters. length() exists for readability; size() matches the other containers.

How do I convert a string to uppercase in C++?

Loop with for (char& c : s) c = std::toupper(static_cast<unsigned char>(c)); or use std::transform. For full Unicode text a library such as ICU is needed.

When should I use std::string_view?

For function parameters that only read text, and for cheap substrings while the original string is alive. Store std::string when you need to keep the text.

Where can I learn more?

Read C++ std::string and std::optional, variant and format, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links