开发者

replacing double space to single space

How can I replace the double space into single space using C++

ex:

"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;
    }
}


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.

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜