</>CodexBash
C++
C++Beginner10 min

Strings

The string type, indexing and length, changing strings in place, substr, find, comparing, converting to and from numbers, and walking a string character by character.

Indexing and slicing a stringstep 1/5
p
0
y
1
t
2
h
3
o
4
n
5
s = pythonlen = 6
Each character has a position, starting at 0. A string of length 6 has positions 0 to 5.

Unlike C, C++ has a real text type, string, that knows its own length and grows as needed.

Creating and reading#

string s = "hello";
s.size()        // 5 (s.length() is the same)
s[0]            // 'h'
s.back()        // 'o'
s.empty()       // false

Positions run from 0 to s.size() - 1. s[i] does not check the range; s.at(i) does, and throws an error if i is out of bounds, which is handy while debugging.

Strings can change#

string s = "cat";
s[0] = 'b';         // "bat"
s += 's';           // "bats"
s += " fly";        // "bats fly"
s.push_back('!');   // "bats fly!"
s.pop_back();       // "bats fly"

Appending with += is fast. Building a long string with s = s + x in a loop copies the whole string every time; use += instead.

Pieces and searching#

string s = "programming";
s.substr(3, 4)          // "gram": 4 characters from position 3
s.substr(7)             // "ming": from 7 to the end
s.find("gram")          // 3
s.find("xyz")           // string::npos, meaning "not found"
s.find('m')             // 6

Always compare a find result with string::npos before using it:

if (s.find("gram") != string::npos) { ... }

Comparing#

==, !=, < and > compare strings by content, alphabetically by character code:

string a = "apple", b = "banana";
a == "apple"    // true
a < b           // true

Uppercase letters sort before lowercase, so "Zebra" < "apple" is true.

Walking the characters#

int vowels = 0;
for (char c : s) {
    c = tolower(c);
    if (string("aeiou").find(c) != string::npos) vowels++;
}

<cctype> gives isalpha, isdigit, isalnum, isspace, tolower and toupper.

To change characters in place, loop by reference:

for (char &c : s) c = toupper(c);     // s is now all capitals

The & means c is the character in the string itself, not a copy.

Reversing and sorting#

#include <algorithm>
reverse(s.begin(), s.end());     // in place
sort(s.begin(), s.end());        // letters in order: "listen" -> "eilnst"

Sorting two words and comparing them is a quick anagram check.

Numbers and text#

int n = stoi("42");          // text to int
long long big = stoll("9000000000");
double d = stod("3.5");
string t = to_string(123);   // number to text

stoi throws an error if the text is not a number.

Key points#

  • string knows its length (size()) and can grow with +=.
  • substr(pos, len) takes a piece; find returns string::npos when nothing is found.
  • == and < compare by content.
  • for (char &c : s) changes characters in place.
  • stoi, stoll, stod and to_string convert between text and numbers.

Next: decisions with if and switch.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedIs it a palindromeEasy
  2. Not startedCancel out neighbouring pairsEasy
Create a free account to track your progress