Iterating Over Strings

What Are String Operations in C?

Learn the common string operations in C++, including length, access, joining, comparing, searching, extracting, and changing text with std::string.

On this page
  1. Common string operations in C++
  2. Get the length with size() and length()
  3. Access one character with [] and at()
  4. Join strings with + and append()
  5. Compare strings with == and compare()
  6. Search with find()
  7. Extract part of a string with substr()
  8. Insert, erase and replace
  9. C functions from <cstring>
  10. Prefer std::string for new code

Common string operations in C++

The common string operations are the things you do most often with text: find its length, read or change a character, join strings together, compare them, search for text, pull out a part, and insert, erase or replace text.

In C++, most of these are member functions of std::string, so you call them with a dot after the variable name. This article covers those operations with short examples. Because you may also meet older code, it includes the C functions from <cstring> as well.

Get the length with size() and length()

size() and length() return the same value, the number of characters in the string:

#include <iostream>
#include <string>

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

    std::cout << word.size() << '\n';    // 5
    std::cout << word.length() << '\n';  // 5

    return 0;
}

To check for an empty string, use empty(), which returns true when the length is 0.

Access one character with [] and at()

word[i] returns the character at index i without checking the index. word.at(i) checks the index and throws std::out_of_range if it is outside the string. Use at() when the index comes from outside your code, such as user input. Use [] when you already know the index is valid.

#include <iostream>
#include <string>

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

    std::cout << word[0] << '\n';     // H
    std::cout << word.at(4) << '\n';  // o

    return 0;
}

Join strings with + and append()

The + operator builds a new string from two strings, or from a string and a character or literal. At least one side must be a std::string, because two string literals cannot be added with +. For more on this, see how to concatenate strings in c.

append() adds text to the end of an existing string:

#include <iostream>
#include <string>

int main() {
    std::string first = "Hello";
    std::string second = "world";

    std::string joined = first + ", " + second + "!";
    std::cout << joined << '\n';  // Hello, world!

    first.append("!!");
    std::cout << first << '\n';   // Hello!!

    return 0;
}

Compare strings with == and compare()

The ==, != and < operators compare strings by their characters. Uppercase and lowercase letters are different characters, so "Apple" and "apple" are not equal. compare() returns 0 when two strings are equal, and it is useful when you need an ordering rather than a yes or no answer.

#include <iostream>
#include <string>

int main() {
    std::string a = "apple";
    std::string b = "apple";

    if (a == b) {
        std::cout << "Same\n";
    }

    return 0;
}

For more on this topic, see how to compare two strings in c.

Search with find()

find() looks for a substring or a character and returns the index where it first appears. If the text is not found, it returns std::string::npos, so check for that value before you use the result:

#include <iostream>
#include <string>

int main() {
    std::string sentence = "The quick brown fox";

    std::string::size_type pos = sentence.find("quick");

    if (pos != std::string::npos) {
        std::cout << "Found at index " << pos << '\n';  // Found at index 4
    }

    return 0;
}

For a single character, see how to locate a character in a string.

Extract part of a string with substr()

substr(pos, count) returns a new string that starts at pos and holds up to count characters. If you leave out count, it returns everything from pos to the end. It throws std::out_of_range if pos is greater than size().

#include <iostream>
#include <string>

int main() {
    std::string sentence = "The quick brown fox";

    std::string part = sentence.substr(4, 5);
    std::cout << part << '\n';  // quick

    return 0;
}

Insert, erase and replace

These functions change the string itself. Each call updates the same variable, so the next line sees the new text:

#include <iostream>
#include <string>

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

    word.insert(5, ",");         // "Hello, world"
    word.erase(0, 1);            // "ello, world"
    word.replace(0, 4, "Help");  // "Help, world"

    std::cout << word << '\n';   // Help, world

    return 0;
}

C functions from <cstring>

Older code often uses functions from <cstring> on C-style strings, which are char arrays ending with a null character:

  • std::strlen returns the number of characters before the null character.
  • std::strcpy copies one C-style string into a char array.
  • std::strcat appends one C-style string to the end of another.
  • std::strcmp compares two C-style strings and returns 0 when they are equal.

These functions do not check the size of the destination array. A copy or append that runs past the end of the array has undefined behavior, which is one reason std::string is usually the safer choice for new code. The example below needs a destination array large enough for the result:

#include <cstring>
#include <iostream>

int main() {
    char name[10] = "Ada";
    std::strcat(name, " L");

    std::cout << name << '\n';                // Ada L
    std::cout << std::strlen(name) << '\n';   // 5

    return 0;
}

Prefer std::string for new code

For most new C++ code, std::string covers these operations with less risk. Once you know which operation you need, the next step is often looping over the characters. See how to iterate through a string in c.

The complete guide to iterating over strings

How to Iterate Through a String in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

SOLID Principles in C++

Learn the five SOLID principles in C++ with short examples of single responsibility, open/closed, Liskov, interface segregation and dependency inversion.