std::string s;But really, to do real-world string processing, you usually need a lot more than this.
cin>>s;
cout<<"I read the string '"<<s<<"'\n";
std::string s;First, you often want to be able to look at characters inside the string. Use "at" or "operator[]", which takes the index of the character you want (for example, s.at(0) gives the first character in the string):
getline(cin,s);
cout<<"I read the string '"<<s<<"'\n";
std::string s;
getline(cin,s);
for (unsigned int i=0;i<s.size();i++)
cout<<"the string has the letter "<<s.at(i)<<"\n";
std::string s="a banana";This returns 3, because the first copy of "an" starts at character index 3. "size_t" is just an unsigned long integer (I'd have been happier if they'd just returned "int"!).
size_t a=s.find("an");
return a;
std::string s="a banana";You can check for this huge value, and respond in some way:
size_t a=s.find("cat");
cout<<"found at index "<<a<<"\n";
std::string s="a banana";
size_t a=s.find("cat");
if (a==std::string::npos)
cout<<"not found\n";
else
cout<<"found at index "<<a<<"\n";
std::string s="a banana";
size_t a=s.find("an",4);
return a;
Here's how you loop over all the ocurrences of a substring.
Notice I start looking at index 0, and stop when "find" returns npos:
std::string s="a banana";
size_t a=0;
while (true) {
a=s.find("an",a);
if (a!=std::string::npos) cout<<"Found substring at index "<<a<<"\n";
else break;
a++; //<- subtle: skip over this substring
}