c++ - 将双空格替换为单空格

标签 c++

如何使用 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/

相关文章:

c++ - CMake - 取决于另一个 cmake 项目

c++ - 龟兔赛跑模拟终止问题

C++ 错误 : Does not name a type, 模板化类

c++ - 向列表中添加一个新元素,并返回对该元素的引用?

c++ - 如何停止应用程序执行

c++ - 为什么添加空格会使编译器进入无限循环?

c++ - 围绕标量初始值设定项错误的大括号

c++ - 关于const或friendship的使用

c++ - 低对比度图像分割

c++ - 如何在 C++ 中删除换行符