8.11.5 搜索字符串(1)
搜索string对象中给定字符或子字符串的find()函数有4个版本,分别列出在表8-3中。所有find()函数都定义为const。
表 8-3
|
函 数
|
说 明
|
|
size_t find(
char ch,
size_t offset=0)
|
在string对象中搜索从offset索引位置开始的
字符ch。可以省略第二个实参,在这种情况下默认值为0
|
|
size_t find(
char char* pstr,
size_t offset=0)
|
在string对象中搜索从offset索引位置开始的
以空字符结尾的字符串pstr。可以省略第二个
实参,在这种情况下默认值为0
|
|
size_t find(
const char* pstr,
size_t offset,
size_t count)
|
在string对象中搜索从offset索引位置开始的
以空字符结尾的字符串pstr的前count个字符
|
|
size_t find(
const string& str,
size_t offset=0)
|
在string对象中搜索从offset索引位置开始的字
符串对象str。可以省略第二个实参,
在这种情况下默认值为0
|
find()函数的各个版本都返回发现的字符或子字符串的第一个字符的索引位置。如果没有找到要找的条目,该函数会返回值string::npos。后一个值是在string类中定义的一个常量,表示string对象中的一个非法位置,它通常用来标识搜索失败。
下面的代码片段显示了find()函数的部分用法:
- string phrase("So near and yet so far");
- string str("So near");
- cout << phrase.find(str) << endl; // Outputs 0
- cout << phrase.find("so far") << endl; // Outputs 16
- cout << phrase.find("so near") << endl; // Outputs string::npos = 4294967295
string::nops的值可能根据不同的编译器实现而不同,因此为了测试它,应该总是使用string::npos,而不是使用显式的值。
下面是反复扫描同一个字符串以搜索特定子字符串的又一示例:
- string str( "Smith, where Jones had had \"had had\", \"had had\" had."
- " \"Had had\" had had the examiners' approval.");
- string substr("had");
- cout << "The string to be searched is:"
- << endl << str << endl;
- size_t offset(0);
- size_t count(0);
- size_t increment(substr.length());
- while(true)
- {
- offset = str.find(substr, offset);
- if(string::npos == offset)
- break;
- offset += increment;
- ++count;
- }
- cout << endl << " The string \"" << substr
- << "\" was found " << count << " times in the string above."
- << endl;
这段代码搜索字符串str,查看其中出现"had"的次数。此搜索在while循环中完成,其中offset记录发现的位置,该位置也用作搜索的起始位置。该搜索从索引位置0(字符串的开头)开始,每次发现子字符串时,就将下一次搜索的新起始位置设置为发现的位置加上子字符串的长度。这样可以确保绕过发现的子字符串。每次发现子字符串时,就递增count。如果find()返回string::npos,就表示没有发现子字符串,搜索结束。执行该代码片段产生如下输出:
- The string to be searched is:
- Smith, where Jones had had "had had", "had had" had. "Had had" had had the
- examiners' approval.
- The string "had" was found 10 times in the string above.