简体   繁体   中英

removing multiple spaces in c++ from string

I have the following code to open a file and read the data from it, then take the relavent part and print it to screen.

char* search = "model name";
int Offset;
string Cpu;
ifstream CpuInfo;
CpuInfo.open ("/proc/cpuinfo");

if(CpuInfo.is_open())
{
  while(!CpuInfo.eof())
  {
    getline(CpuInfo,Cpu);
    if ((Offset = Cpu.find(search, 0)) != string::npos)
    {
       //cout << "found '" << search << " " << line << endl;
       break;
    }
  }
  CpuInfo.close();
}
Cpu.replace (0,13,"");

cout << Cpu

This usually outputs the type of CPU your using, but one problem is that some people have various spaces inbetween the words that it prints out.

My question is how to remove all the spaces from inbetween the words. They can of random ammount and aren't always present.

Thank you in advance.

Since your question states: "how to remove all the spaces from inbetween the words" :

You can use std::remove_if from the standard <algorithm> library in addition to std::isspace :

std::string mystring = "Text with some   spaces";
std::remove_if(mystring.begin(), mystring.end(), std::isspace);

This now becomes:

Textwithsomespaces

REFERENCES: http://en.cppreference.com/w/cpp/algorithm/remove

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM