4.5.5 搜索以空字符结尾的字符串
strspn()函数可以搜索字符串中不包含在给定集合中的第一个字符,并返回该字符的索引。第一个参数是指向要搜索的字符串的指针,第二个参数是指向包含该字符集合的字符串的指针。
- char* str = "I agree with everything.";
- char* vowels = "aeiouAEIOU ";
- size_t index = strspn(str, vowels);
- cout << "The first character that is not a vowel is '" << str[index]
- << "' at position " << index << endl;
这段代码在str中搜索第一个字符不在vowels中的字符串。注意,vowels集合中包括一个空格,因此在搜索时会忽略空格。这段代码的输出为:
The first character that is not a vowel is 'g' at position 3
strspn()函数的返回值表示第一个参数字符串落在第二个参数字符串中的子串长度。在本例中该子串是"I a"。
wcspn()函数是strspn()的宽字符串版本。
strstr()函数返回一个指针,指向第一个参数中第二个参数指定的子串的位置。下面的代码显示了运行中的strstr()函数:
- char* str = "I agree with everything.";
- char* substring = "ever";
- char* psubstr = strstr(str, substring);
-
- if(!psubstr)
- cout << "\"" << substring << "\" not found in \"" << str << "\"" << endl;
- else
- cout << "The first occurrence of \"" << substring
- << "\" in \"" << str << "\" is at position "
- << psubstr-str << endl;
第三个语句调用strstr()函数,在str中搜索子串第一次发生的位置。该函数返回一个指向子串位置的指针(如果找到了),如果没有找到,则返回NULL。if语句根据有没有在str中找到substring返回一条消息。表达式psubstr-str给出了子串中第一个字符的索引位置。这段代码产生的输出是:
- The first occurrence of "ever" in "I agree with everything." is at position 13
试一试 搜索以空字符结尾的字符串
本示例搜索一个给定的字符串来确定给定子串出现的次数。代码如下:
- //Ex4_12.cpp
- // Searching a string
- #include <iostream>
- #include <cstring>
- using std::cout;
- using std::endl;
- using std::strlen;
- using std::strstr;
-
- int main()
- {
- char* str = "Smith, where Jones had had \"had had\" had had \"had\"."
- "\n\"Had had\" had had the examiners' approval.";
-
- char* word = "had";
- cout << "The string to be searched is: "
- << endl << str << endl;
-
- int count = 0;
// Number of occurrences of word in str - char* pstr = str;
// Pointer to search start position - char* found = 0;
// Pointer to occurrence of word in str -
- while(true)
- {
- found = strstr(pstr, word);
- if(!found)
- break;
- ++count;
- pstr = found+strlen(word);
- // Set next search start as 1 past the word found
- }
-
- cout << "\"" << word << "\" was found "
- << count << " times in the string." << endl;
- return 0;
- }
这个示例的输出为:
- The string to be searched is: Smith,
where Jones had had "had had" had had "had". - "Had had" had had the examiners' approval.
- "had" was found 10 times in the string.
示例说明
所有动作都发生在不确定的while循环中:
- while(true)
- {
- found = strstr(pstr, word);
- if(!found)
- break;
- ++count;
- pstr = found+strlen(word);
- // Set next search start as 1 past the word found
- }
第一步是在字符串中从位置pstr开始搜索word,它最初是字符串的开头。我们将strstr()返回的地址存储在found中;如果在str中没有找到word,返回值就为空值。因此,在这种情况下if语句会结束循环。
如果found不为空,我们就递增word的出现次数,并更新pstr指针,使它指向在str中找到的word实例后面的那个字符。它将是在下一个循环迭代上搜索的起点。
从输出中可以看出在str中找到了10次word。当然"Had"不计数,因为它是大写字母开头的。