๐ŸŽ“ A1Learner
๐Ÿ”

C++ String Functions

String functions are operations that inspect or change the text in a string. Each operation is written after the string, with a dot before its name.

Counting characters

length() counts the characters in the string. The word Hello has five characters.

#include <iostream>
#include <string>

int main() {
  std::string word = "Hello";
  std::cout << word.length() << std::endl;
  return 0;
}

Growing a string with append

The first line prints the string as it starts. append adds text to the end, and the second line prints the grown string.

#include <iostream>
#include <string>

int main() {
  std::string word = "Hello";
  std::cout << word << std::endl;
  word.append(", Hana");
  std::cout << word << std::endl;
  return 0;
}

Finding a piece of text

find looks for the piece gram inside the string. The piece starts at index 3, so the program prints 3.

#include <iostream>
#include <string>

int main() {
  std::string word = "Programming";
  std::cout << word.find("gram") << std::endl;
  return 0;
}

Taking a piece with substr

substr starts at index 0 here. It takes four characters from the start of the string.

#include <iostream>
#include <string>

int main() {
  std::string word = "Programming";
  std::cout << word.substr(0, 4) << std::endl;
  return 0;
}

Example

#include <iostream>
#include <string>

int main() {
  std::string email = "hana@example.com";
  int at = email.find("@");
  std::cout << "User: " << email.substr(0, at) << std::endl;
  std::cout << "Domain: " << email.substr(at + 1, email.length() - at - 1) << std::endl;
  return 0;
}

Key points

  • Use length() to count the characters in a string.
  • Use append to add text to the end of a string.
  • Use find to get the starting index of a piece of text.
  • Use substr to take a piece out of a string.
  • substr takes a starting index and a count of characters.
  • A dot joins an operation to the string it works on.

In this example, email holds one address. find gives the index of the @ sign, and that index is stored in at. The first substr takes the text before the sign as the user name. The second substr takes the text after the sign as the domain.

Note

A starting index counts from 0, like the index of a single character.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

What does length() give for the string "Hello"?