如何使用 C++ 将双空格替换为单空格
例如:
"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;
关于c++ - 将双空格替换为单空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4913894/