Substrings in C++

Level 3131 keystrokes

substr(pos, len) copies part of a string, and find returns the index where a substring starts. Prints Hello, World and 6.

C++ code

1string text = "Hello World";
// substr(0, 5) takes 5 characters starting at index 0: Hello
2cout << text.substr(0, 5) << endl;
// With only a start position, substr takes the rest of the string: World
3cout << text.substr(6) << endl;
// find returns the index of the first match (6); if nothing is found it returns string::npos
4cout << text.find("World") << endl;

Output

Hello
World
6
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 12
  • ;× 4
  • "× 4
  • .× 3
  • (× 3
  • )× 3
  • ,× 1
  • =× 1

More C++ examples at level 3

← C++ typing practice