c++字符替换问题

来源:百度知道 编辑:UC知道 时间:2024/05/27 00:03:24
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
main()
{
string text,word,replace_word,separators=" ,.\"";
size_t start=text.find_first_not_of(separators),end=0;
cout<<"input the string terminated by #:"<<endl;
std::getline(cin,text,'#');
cout<<"input the word to be replaced:"<<endl;
cin>>word;
cout<<"enter the replace word:"<<endl;
cin>>replace_word;
while(start!=string::npos)
{
end=text.find_first_of(separators,start+1);
if(end==string::npos)end=text.length();
if(text.compare(start,end-start,word)==0)text.replace(start,end-start,replace_word);
start=text.find_first_not_of(separators,end+1);
}
cout<<text<<endl;
}

其中start总是一开始就是string::npos,为什么会这样?

改两个地方
1 在 while 循环之前加:
start=text.find_first_not_of(separators);
2 在 while 循环内改一下这个:
if(end==string::npos)end=text.length() - 1;
注意要减 1 !!!

//---------------------------------------------------------------------------

#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
main()
{
string text,word,replace_word,separators=" ,.\"";
size_t start,end=0;////////////////////////////////
cout<<"input the string terminated by #:"<<endl;
std::getline(cin,text,'#');
cout<<"input the word to be replaced:"<<endl;
cin>>word;
cout<<"enter the replace word:"<<endl;
cin>>replace_word;
start=text.find_first_not_of(separators);//////////////////////////
while(start!=string::npos)
{
end=text.find_fi