Game Development Reference
In-Depth Information
Listing 13-15. The string::find Method
string myString{ "This is my string!" };
void FindInString(string myString)
{
size_t found = myString.find("is");
if (found != string::npos)
{
cout << "\" is\" found at position: " << found << endl;
}
found = myString.find("is", found+1);
if (found != string::npos)
{
cout << "is found at position: " << found << endl;
}
}
The example in Listing 13-15 shows two different versions of found. The first finds the first instance
of “is” in the string and returns the index where it can be found. This first call will return 2 for the is
that makes up part of This. The find method will return the constant value string::npos if it fails to
find the supplied data. We can then call find again and pass in the start position for the search.
In our example we pass in the position of the previously found instance and add 1 to skip over
it. This second call returns 5 when it finds the word is. The rfind method will carry out the same
operation but search backward through the string and myString.rfind("is") would return 5. rfind
can also take a position value to start working back from.
It's also possible to search for a single character in a supplied set using find_first_of . Listing 13-16
shows this method in action.
Listing 13-16. The string::find_first_of Method
found = myString.find_first_of("msg");
if (found != string::npos)
{
cout << "is found at position: " << found << endl;
}
This method does not look for the entire phrase msg ; instead it looks for m , s, and g individually.
In our example the first of these characters is the s in This and therefore the method returns 3.
There are also complementary methods find_last_of , find_first_not_of , and find_last_not_of .
These methods behave as you would expect: find_last_of finds the last character in the supplied
set, find_first_not_of finds the first character not in the set, and find_last_not_of finds the last
character not in the set.
Formatting Data with stringstream
If you've used the C or C++ programming languages in the past, you might be familiar with the
printf method for formatting string data. Even today many C++ programmers still use this older
C-style method of formatting data for use within strings. This topic, however, covers the more
modern method for formatting string data, using iostream modifiers . You have already seen some
 
Search WWH ::




Custom Search