如何使用 C++ 将双空格替换为单空格
ex:
"1 2 3 4 5" => "1 2 3 4 5"
这就是我到目前为止所做的:
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 循环中,使用此代码。
while((loc = line.find(" ")) != std::string::npos) //Two spaces here
{
line.replace(loc,2," "); //Single space in quotes
}
cout << line << endl;
就是这样。我还没有尝试过,请告诉我是否有效。
正如 Fred 指出的,在 splitLines 函数中使用引用传递。上述解决方案是次正规的,复杂度为 O(n^2)。这个比较好。
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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)