Strings

Programming Languages · C++ Going Further · 12 min

Join, measure, slice and search text with std::string.

Joining strings

+ glues strings together. Add a " " in the middle if you want a space:

std::string a = "ice";
std::string b = "cream";
std::string treat = a + " " + b;   // "ice cream"
  • Create a std::string full that joins first, a space, and last.

  • Print full.

How long is it?

.length() tells you how many characters a string has. Spaces count too:

std::string pet = "cat";
std::cout << pet.length() << "\n";   // 3
  • Print how many letters word has, with word.length().

  • If word.length() is greater than 6, print Long word.

One letter at a time

Like a vector, a string has indexes starting at 0. name[0] is the first character. The last one is at length() - 1:

std::string pet = "cat";
std::cout << pet[0] << "\n";                  // c
std::cout << pet[pet.length() - 1] << "\n";   // t
  • Print the first letter of name with name[0].

  • Print the last letter using name.length() - 1 as the index.

Cutting out a piece: substr

substr(start, count) gives you a piece of a string: start at an index, take count characters:

std::string word = "sunflower";
std::cout << word.substr(0, 3) << "\n";   // sun
std::cout << word.substr(3, 6) << "\n";   // flower
  • Print the year: date.substr(0, 4).

  • Print the month: 2 characters starting at index 5.

Searching with find

find looks for some text and gives back the index where it starts. If it isn't there, you get std::string::npos, a special "not found" value:

std::string s = "hello";
std::cout << s.find("ll") << "\n";   // 2
if (s.find("z") == std::string::npos) {
    std::cout << "No z\n";
}
  • Print where "C++" starts in sentence.

  • If sentence.find("Java") equals std::string::npos, print No Java here.

Put it together: email splitter

Split an email address into the user and the domain. Find the @, then cut on each side of it.

Tip: substr with only a start index takes everything to the end: email.substr(4).

  • Store the position of "@" in an int called at, using find.

  • Print User: ada using email.substr(0, at).

  • Print Domain: example.com using email.substr(at + 1).

More in C++ Going Further

Previous: Functions · Next: References & Pointers