簡體   English   中英

在字符串C ++ Boost問題中替換空格

[英]replace whitespace in an string c++ boost problem

我正在使用此代碼替換while空間,但是它永遠不會替換所有空白,您能告訴我我錯了嗎?

#include <iostream>
#include <string>
#include <boost/regex.hpp>
#include<boost/algorithm/string.hpp>
#include<boost/algorithm/string/replace.hpp>

using namespace std;

int main(void)
{
        string s4="Hai ad                     asdasd                       asdasd";
        cout << boost::algorithm::replace_all_copy(s4, "    ", " ");
}

您的代碼將每個出現的4個空白替換為一個空白。 由於存在4個空白模式,因此在輸出中再次獲得了多個(單個)空白。

我不確定您要達到的目標。 但是,要擦除所有空格,最好使用erase_all_copy() 或者要消除所有出現的4個空白,請遵循Potatoswatters的建議。

#include <iostream>
#include <string>
#include<boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/erase.hpp>

using namespace std;

int main(void) {
        string s4="Hai ad                     asdasd                       asdasd";

        cout << boost::algorithm::erase_all_copy( s4, " " ) << endl;
        cout << boost::algorithm::replace_all_copy( s4, "    ", "") << endl;
}

還是您的目標是刪除單詞之間的所有空白(除了一個空格)?

流運算符會自動刪除多余的空白

#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <algorithm>

using namespace std;

int main()  // Note: main(void) is not valid
{
    string s4="Hai ad                     asdasd                       asdasd";


    // Technique 1: Simple
    std::stringstream  s4Stream(s4);

    std::string s5;
    std::string word;
    while(s4Stream >> word)
    {
        s5.append(word).append(" ");
    }
    std::cout << s4 << "\n" << s5 << "\n";


    // Technique2: Using STL algorithms
    std::stringstream s4bStream(s4);
    std::stringstream s5bStream;

    std::copy(std::istream_iterator<std::string>(s4bStream),
              std::istream_iterator<std::string>(),
              std::ostream_iterator<std::string>(s5bStream," ")
             );

    std::string       s5b = s5bStream.str();
    std::cout << s4 << "\n" << s5b << "\n";
}

如果想法是用單個空格替換任意數量的空格,則可以欺騙標准的unique(_copy)算法來做到這一點:

#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <boost/lambda/lambda.hpp>

std::string remove_excessive_spaces(const std::string& s)
{
     using namespace boost::lambda;
     std::string result;
     //consider consequtive chars equal only if they are both spaces.
     unique_copy(s.begin(), s.end(), back_inserter(result), _1 == ' ' && _2 == ' ');
     return result;
}

int main(void)
{
    std::string s4="Hai ad                     asdasd                       asdasd";
    std::cout << remove_excessive_spaces(s4);
}

如果要完全消除空格,則最后一個參數應為空字符串。

     cout << boost::algorithm::replace_all_copy(s4, "    ", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM