2012-11-30 111 views
1

我需要從行中刪除多餘的空格,如1.47\t\t4.32 5.1 \t\tf41.4。 我怎麼能做到這一點與提升?C++刪除字符串中的多餘空格或製表符

+0

你是什麼意思的額外空間? 是否要將其更改爲「1.474.325.1f41.4」? – Osiris

+2

無需提升。如果你不需要空格,'std :: remove_if'和'isspace'應該這樣做。另一方面,如果你只想刪除足夠的空格,而其他字符之間只有一個空格,[this](http://stackoverflow.com/questions/3606597/replace-whitespace-in-an-string-c-助推 - 問題)看起來可能有所幫助。 – chris

+0

奧西里斯,對不起,但字符串時,我發佈的問題刪除額外的空間:D。不,我有數字,然後兩個空格然後數字。我需要字符串號碼一個空格號碼。 –

回答

2

如果你只想做很容易,我會使用這樣的:

std::string single_space(std::string const &input) { 
    std::istringstream buffer(input); 
    std::ostringstream result; 

    std::copy(std::istream_iterator<std::string>(buffer), 
       std::istream_iterator<std::string>(), 
       std::ostream_iterator<std::string>(result, " ")); 
    return result.str(); 
} 

如果你關心使它儘可能地快,你可能想看看另一個question from earlier today

0

我找到了我的問題的答案。

std::string trim(const std::string& str, 
       const std::string& whitespace = " \t") 
{ 
    const auto strBegin = str.find_first_not_of(whitespace); 
    if (strBegin == std::string::npos) 
     return ""; // no content 

    const auto strEnd = str.find_last_not_of(whitespace); 
    const auto strRange = strEnd - strBegin + 1; 

    return str.substr(strBegin, strRange); 
} 

std::string reduce(std::string& str, 
        const std::string& fill = " ", 
        const std::string& whitespace = " \t") 
{ 
    // trim first 
    auto result = trim(str, whitespace); 
    // replace sub ranges 
    auto beginSpace = result.find_first_of(whitespace); 
    while (beginSpace != std::string::npos) 
    { 
     const auto endSpace = result.find_first_not_of(whitespace, beginSpace); 
     const auto range = endSpace - beginSpace; 

     result.replace(beginSpace, range, fill); 

     const auto newStart = beginSpace + fill.length(); 
     beginSpace = result.find_first_of(whitespace, newStart); 
    } 

    return result; 
} 
0

這是一個非常簡單的刪除多餘空格的實現。

#include <iostream> 
std::string trimExtraWhiteSpaces(std::string &str); 
int main(){ 
    std::string str = " Apple is a  fruit . "; 
    str = trimExtraWhiteSpaces(str); 
    std::cout<<str; 
} 
std::string trimExtraWhiteSpaces(std::string &str){ 
    std::string s; 
    bool first = true; 
    bool space = false; 
    std::string::iterator iter; 
    for(iter = str.begin(); iter != str.end(); ++iter){ 
     if(*iter == ' '){ 
      if(first == false){ 
       space = true; 
      } 
     }else{ 
      if(*iter != ',' && *iter != '.'){ 
       if(space){ 
        s.push_back(' '); 
       } 
      } 
      s.push_back(*iter); 
      space = false; 
      first = false; 
     } 
    } 
    return s; 
} 
相關問題