STL中string find函数怎么用

Coolear 2008-12-14 01:06:32
#include <iostream>
#include <string>
using namespace std;

int main()
{
string s;
while(cin>>s)
{
string::size_type j=-1;
for(string::size_type i=0;i!=s.size ();++i)
{
char c=s[i];
j=s.find (c,i);//我的j每次总是输出0,也许使用方法不当吧,请问该如何
//才能让j为s中等于s[i]的index呢?
if(j!=-1)
break;
}
cout<<j;
}
return 0;
}
...全文
1733 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Coolear 2008-12-14
  • 打赏
  • 举报
回复
感谢1 2 3楼,问题的确如此,修改后的代码就符合了:
#include <iostream>
#include <string>
using namespace std;

int main()
{
string s;
while(cin>>s)
{
string::size_type j=-1;
for(string::size_type i=0;i!=s.size ()-1;++i)
{
char c=s[i];
j=s.find (c,i+1);
//If found, the index of this matching character is returned. If not found, npos is returned.
if(string::npos==j)
{
j=-1;
}
if(string::npos!=j)
break;
}
cout<<j;
}
return 0;
}
SearchLife 2008-12-14
  • 打赏
  • 举报
回复
if(j!=-1)
break;
因为有这句
wiowei 2008-12-14
  • 打赏
  • 举报
回复
[Quote=引用楼主 coolwater2009 的帖子:]
#include <iostream>
#include <string>
using namespace std;

int main()
{
string s;
while(cin>>s)
{
string::size_type j=-1;
for(string::size_type i=0;i!=s.size ();++i)
{
char c=s[i];
j=s.find(c,i);//从i位置开始搜索c,没什么问题。如果find(c)则是全字符串搜索
if(j!=-1) //问题在这一句:初始i为0,找到的第一个c位置也是为0,因此j为0,所以break;
break;
}
cout < <j;
}
return 0;
}
[/Quote]
与find函数无关,是你自己程序问题,你可以改为这样试试:
for(string::size_type i=0;i!=s.size ();++i)
{
char c=s[i];
j=s.find(c,i);
cout < <j;
}
就呆在云上 2008-12-14
  • 打赏
  • 举报
回复
修改如下:
#include <iostream> 
#include <string>
using namespace std;

int main()
{
string s;
while(cin>>s)
{
string::size_type j=-1;
for(string::size_type i=0;i<s.size ();++i)
{
char c=s[i];
j=s.find(c);//我的j每次总是输出0,也许使用方法不当吧,请问该如何
//才能让j为s中等于s[i]的index呢?
if(j == -1)
break;
}
cout <<j;
}
return 0;
}

65,211

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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