C++中STL在string中查找字符或子字符串

C++中STL在string中查找字符或子字符串

STL string 类提供了成员函数 find(),该函数有多个重载版本,可在给定 string 对象中查找字符或
子字符串。

// Find substring "day" in sampleStr, starting at position 0
size_t charPos = sampleStr.find ("day", 0);
// Check if the substring was found, compare against string::npos
if (charPos != string::npos)
cout << "First instance of "day" was found at position " << charPos;
else
cout << "Substring not found." << endl;

程序清单 16.4 演示了 std::string::find()的用法。

0: #include <string>
1: #include <iostream>
2:
3: int main ()
4: {
5: using namespace std;
6:
7: string sampleStr ("Good day String! Today is beautiful!");
8: cout << "Sample string is:" << endl << sampleStr << endl << endl;
9:
10: // Find substring "day" - find() returns position
11: size_t charPos = sampleStr.find ("day", 0);
12:
13: // Check if the substring was found...
14: if (charPos != string::npos)
15: cout << "First instance \"day\" at pos. " << charPos << endl;
16: else
17: cout << "Substring not found." << endl;
18:
19: cout << "Locating all instances of substring \"day\"" << endl;
20: size_t subStrPos = sampleStr.find ("day", 0);
21:
22: while (subStrPos != string::npos)
23: {
24: cout << "\"day\" found at position " << subStrPos << endl;
25:
26: // Make find() search forward from the next character onwards
27: size_t searchOffset = subStrPos + 1;
28:
29: subStrPos = sampleStr.find ("day", searchOffset);
30: }
31:
32: return 0;
33: }

输出:

Sample string is:
Good day String! Today is beautiful!
First instance "day" at pos. 5
Locating all instances of substring "day"
"day" found at position 5
"day" found at position 19

分析:
第 11~17 行演示了 find()函数的最简单用法,它判断在 string 中是否找到了特定子字符串。这是
通过将 find()操作的结果与 std::string::npos(实际值为-1)进行比较实现的, std::string::npos 表明没有
找到要搜索的元素。 如果 find()函数没有返回 npos, 它将返回一个偏移量, 指出子字符串或字符在 string
中的位置。
这段代码演示了如何在 while 循环中使用 find()函数在 STL string 查找指定字符或子字符串的所有
实例。这里使用的 find 函数的重载版本接受两个参数:要搜索的子字符串或字符以及命令 find()从哪里
开始搜索的偏移量。在第 29 行,我们就通过指定偏移量,让 find()搜索下一个指定的子字符串。
STL string 还有一些与 find( )类似的函数,如 find_first_of( )、 find_first_not_of( )、
find_last_of( )和 find_last_not_of( ),这些函数可帮助程序员处理字符串。

对C++编程技术感兴趣的朋友请点击这里:零声学院C/C++服务器课程

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值