find()函数的奇怪结果

imeng99 2003-07-28 09:47:34
#include <iostream>
#include <string>

using namespace std;

int main()
{
const string name( "AnnaBelle" );
for( int i = 0; i < name.size(); ++ i )
{
cout << i << endl;
string::size_type pos = name.find( "Belle", 0, i );
if( pos == string::npos )
cout << "Belle not found!\n";
else
cout << "Belle found at pos: " << pos << endl;
}

return 0;
}
/*
// 输出结果
1
Belle found at pos: 4
2
Belle found at pos: 4
3
Belle found at pos: 4
4
Belle found at pos: 4
5
Belle found at pos: 4
6
Belle not found!
7
Belle not found!
8
Belle not found!
Press any key to continue
*/
这个结果完全和我想象的不同,为什么会有这样的结果?
...全文
39 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
njtu 2003-07-29
  • 打赏
  • 举报
回复
同意micropentium6(小笨)

to fixopen(dup) ( ):
name.find( "Belle", 0, 0 ); 返回 0(第一个位置)
fixopen 2003-07-29
  • 打赏
  • 举报
回复
size_type find(const value_type* p, size_type off = 0, size_type count) const;

如果micropentium6(小笨)那样的程序,得出这样的结果是正常的。

那 imeng99(凌晨两三点) 的结果怎样理解呢?BTW
结果是:
0
Belle found at pos: 0
1
Belle found at pos: 4
2
Belle found at pos: 4
3
Belle found at pos: 4
4
Belle found at pos: 4
5
Belle found at pos: 4
6
Belle not found!
7
Belle not found!
8
Belle not found!

我的第零个结果是0

惊讶于结果,不懂count参数的含义
imeng99 2003-07-28
  • 打赏
  • 举报
回复
to micropentium6(小笨):
find的第二个参数指明查找的开始位置,第三个参数指明查找的结束位置。
  • 打赏
  • 举报
回复
你想要什么?find的第三个参数指明匹配的字符数的
我想你要的是这个
#include <iostream>
#include <string>

using namespace std;

int main()
{
const string name( "AnnaBelle" );
for( int i = 0; i < name.size(); ++ i )
{
cout << i << endl;
string::size_type pos = name.find( "Belle", i, 5 ); //!
if( pos == string::npos )
cout << "Belle not found!\n";
else
cout << "Belle found at pos: " << pos << endl;
}

return 0;
}
0
Belle found at pos: 4
1
Belle found at pos: 4
2
Belle found at pos: 4
3
Belle found at pos: 4
4
Belle found at pos: 4
5
Belle found at pos: 4
6
Belle not found!
7
Belle not found!
8
Belle not found!
Press any key to continue

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧