簡體   English   中英

如何使用帶有除空格以外的其他分隔符的 istringstream 拆分字符串?

[英]How to split string using istringstream with other delimiter than whitespace?

以下技巧使用istringstream將字符串拆分為空格。

int main() {
    string sentence("Cpp is fun");
    istringstream in(sentence);
    vector<string> vec = vector<string>(istream_iterator<string>(in), istream_iterator<string>());
    return 0;
}

是否有類似的技巧可以用any分隔符分割字符串? 例如, | 在“Cpp|is|fun”中。

一般來說,istringstream 方法速度慢/效率低,並且至少需要與字符串本身一樣多的內存(當您有一個非常大的字符串時會發生什么?) C++ 字符串工具包庫 (StrTk)為您的問題提供了以下解決方案:

#include <string>
#include <vector>
#include <deque>
#include "strtk.hpp"
int main()
{
   std::string sentence1( "Cpp is fun" );
   std::vector<std::string> vec;
   strtk::parse(sentence1," ",vec);

   std::string sentence2( "Cpp,is|fun" );
   std::deque<std::string> deq;
   strtk::parse(sentence2,"|,",deq);

   return 0;
}

更多例子可以在這里找到

#include <iostream>
#include <string>
#include <sstream>

int main()
{
  std::istringstream iss { "Cpp|is|fun" };

  std::string s;
  while ( std::getline( iss, s, '|' ) )
    std::cout << s << std::endl;

  return 0;
}

演示

以下代碼使用正則表達式查找“​​|” 並將周圍的元素拆分成一個數組。 然后在for循環中使用cout打印每個元素。

此方法允許使用正則表達式進行拆分作為替代方案。

#include <iostream>
#include <string>
#include <regex>
#include <algorithm>
#include <iterator>
    
using namespace std;


vector<string> splitter(string in_pattern, string& content){
    vector<string> split_content;

    regex pattern(in_pattern);
    copy( sregex_token_iterator(content.begin(), content.end(), pattern, -1),
    sregex_token_iterator(),back_inserter(split_content));  
    return split_content;
}
    
int main()
{   

    string sentence = "This|is|the|sentence";
    //vector<string> words = splitter(R"(\s+)", sentence); // seperate by space
    vector<string> words = splitter(R"(\|)", sentence);

    for (string word: words){cout << word << endl;}

}   

暫無
暫無

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

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