Substring

beginner c++11 strings

In C++ std::string provides the substr method for creating a substring from a string. substr is more useful when paired with the “find” methods for locating the start and end locations first.

#include <string>
#include <iostream>

int main() {
  std::string innerPlanets{"Mercury Venus Earth Mars"}; 

  // Copy 5 characters from position 8
  std::cout << innerPlanets.substr(8, 5) << "\n";

  size_t begin = innerPlanets.find("Earth");
  // Copy characters from "Earth" to the end of the string
  std::cout << innerPlanets.substr(begin);
}
Venus
Earth Mars


For more C++ By Example, click here.