
Strings Functions
string :: substr
// string::substr
#include <iostream>
#include <string>
using namespace std;
int main (){
string str="We think in generalities, but we live in details.";
string str2 = str.substr (3,5); // "think"
size_t pos = str.find("live"); // position of "live" in str
string str3 = str.substr (pos); // get from "live" to the end
cout << str2 << ' ' << str3 << '\n';
return 0;
}string :: find()
bool findStr(string haystack, string needle) {
size_t found = haystack.find(needle);
//The position of the first character of the first match.
//If no matches were found, the function returns string::npos.
if(found != string::npos)
return true;
else
return false;
}
int main(){
string haystack = "sabutsad", needle = "sadl";
if(findStr(haystack, needle))
cout << "String found!!";
else
cout << "String not found!!";
}string :: findr()
Find last occurrence of content in string
int main(){
string haystack = "sadbutsad", needle = "sad";
size_t found = haystack.rfind(needle);
// Return the position of the first character of the last match.
if(found != string::npos)
cout << "Last Occurence of String needle in haystack: " << found;
}string :: find_first_of
// string::find_first_of
#include <iostream> // cout
#include <string> // string
#include <cstddef> // size_t
using namespace std;
int main () {
string str ("Please, replace the vowels in this sentence by asterisks.");
size_t found = str.find_first_of("aeiou");
// Return the position of the first character that matches.
while (found!=string::npos){
str[found]='*';
found=str.find_first_of("aeiou", found+1);
}
cout << str << '\n';
return 0;
}string :: find_first_not_of
Find absence of character in string
// string::find_first_not_of
#include <iostream> // cout
#include <string> // string
#include <cstddef> // size_t
using namespace std;
int main (){
string str ("look for non-alphabetic characters...");
size_t found = str.find_first_not_of("abcdefghijklmnopqrstuvwxyz ");
// The position of the first character that does not match.
// If no such characters are found, the function returns string::npos.
if (found!=string::npos)
{
cout << "The first non-alphabetic character is " << str[found];
cout << " at position " << found << '\n';
}
else
cout << "Whole string contain Alphabetic Characters";
}Last updated
Was this helpful?