xxxxxxxxxx
// CPP program to illustrate substr()
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
// Take any string
string s1 = "Geeks";
// Copy two characters of s1 (starting
// from position 3)
string r = s1.substr(3, 2);
// prints the result
cout << "String is: " << r;
return 0;
}
xxxxxxxxxx
// string::substr
#include <iostream>
#include <string>
int main ()
{
std::string str="We think in generalities, but we live in details.";
// (quoting Alfred N. Whitehead)
std::string str2 = str.substr (3,5); // "think"
std::size_t pos = str.find("live"); // position of "live" in str
std::string str3 = str.substr (pos); // get from "live" to the end
std::cout << str2 << ' ' << str3 << '\n';
return 0;
}
xxxxxxxxxx
/ string::substr (pos, len)
#include <iostream>
#include <string>
int main ()
{
std::string str = "We think in generalities, but we live in details.";
// (quoting Alfred N. Whitehead)
std::string str2 = str.substr (3, 5); // "think" (pos, len)
std::size_t pos = str.find("live"); // position of "live" in str
std::string str3 = str.substr (pos); // get from "live" to the end
std::cout << str2 << ' ' << str3 << '\n';
return 0;
}
/*
* this will be the output :--
* "think live in details."
*/
xxxxxxxxxx
// CPP program to illustrate substr()
#include <string.h>
#include <iostream>
using namespace std;
int main()
{
// Take any string
string s1 = "Geeks";
// Copy three characters of s1 (starting
// from position 1)
string r = s1.substr(1, 3);
// prints the result
cout << "String is: " << r;
return 0;
}
xxxxxxxxxx
#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);
}
xxxxxxxxxx
string sub_string=main_string.substr(first_pos_of_the_substring_from_main_string,length_of_the_substring_from_main_string_starting_from_the_first_position