std::string

Dr. Lawlor, CS 202, CS, UAF

OK, so you've seen std::string before:
std::string s;
cin>>s;
cout<<"I read the string '"<<s<<"'\n";

(Try this in NetRun now!)

But really, to do real-world string processing, you usually need a lot more than this.

For example, "cin>>s;" stops reading as soon as it hits a space or newline.  Sometimes you need spaces and newlines, in which case you want to use "getline".  Annoyingly, the method "cin.getline" is horribly broken, taking only bare character arrays.  To read a line into a std::string, use the bare function "std::getline", like this:
std::string s;
getline(cin,s);
cout<<"I read the string '"<<s<<"'\n";

(Try this in NetRun now!)

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):
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";

(Try this in NetRun now!)

Find

The second thing you often need is some way to find things inside your string.  You can compare the entire string with just ==, but that won't find the "an" inside "banana".  For that, you need "find", which returns the index of the first copy of the string it finds:
std::string s="a banana";
size_t a=s.find("an");
return a;

(Try this in NetRun now!)

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"!).

If you look for a character that doesn't exist, find returns "std::string::npos", which is a huge value:
std::string s="a banana";
size_t a=s.find("cat");
cout<<"found at index "<<a<<"\n";

(Try this in NetRun now!)

You can check for this huge value, and respond in some way:
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";

(Try this in NetRun now!)

Find starting at an Index

You can also give "find" a starting index.  Find will look for the string starting at the specified location.  The return value is still a valid index, or std::string::npos.  Here I'm skipping the first copy of "an", at index 3, because I start looking at index 4:
std::string s="a banana";
size_t a=s.find("an",4);
return a;

(Try this in NetRun now!)

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
}

(Try this in NetRun now!)