将双空格替换为单空格 [英] replacing double space to single space
本文介绍了将双空格替换为单空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用C ++将双空格替换为单个空格
How can I replace the double space into single space using C++
例如:
"1 2 3 4 5" => "1 2 3 4 5"
这是我到目前为止所做的:
this is what I`ve done till now:
int _tmain(int argc, _TCHAR* argv[])
{
string line;
ifstream myfile(myFile);
if(myfile.is_open())
{
cout<<"File Opened ...\n";
while(myfile.good())
{
getline(myfile,line);
splitLine(line);
//cout<<line<<endl;
}
}
else
cout<<"File Not Found ...\n";
myfile.close();
return 0;
}
void splitLine(string line)
{
int loc;
cout<<line<<endl;
while(loc = line.find(" "))
{
cout<<loc<<endl;
}
}
推荐答案
在splitLines代码的while循环中,使用此代码.
In while loop of splitLines code, use this code.
while((loc = line.find(" ")) != std::string::npos) //Two spaces here
{
line.replace(loc,2," "); //Single space in quotes
}
cout << line << endl;
就这样.我还没有尝试过,请告诉我它是否有效.
Thats it. I haven't tried it out, let me know if it works.
正如弗雷德指出的那样,在splitLines函数中使用按引用传递.上面的解决方案是次正规的,复杂度为O(n ^ 2).这个更好.
And as fred pointed out, use pass by reference in splitLines function. The above solution is sub-normal and is O(n^2) complexity. This one is better.
int loc = -1;
while((loc = line.find(" ",loc+1)) != std::string::npos) //Two spaces here
{
line.replace(loc,2," "); //Single space in quotes
}
cout << line << endl;
这篇关于将双空格替换为单空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文