簡體   English   中英

如何在C ++中將空格分隔的字符串拆分為多個字符串?

[英]How to split a space separated string into multiple strings in C++?

有點我的代碼如下所示:

static int myfunc(const string& stringInput)
{
    string word;
    stringstream ss;

    ss << stringInput;
    while(ss >> word)
    {
        ++counters[word];
    }
    ...
}

這里的目的是將輸入字符串(由空格''分隔)到字符串變量word ,但這里的代碼似乎有很多開銷 - 將輸入字符串轉換為字符串流並從字符串流中讀取進入目標字符串。

是否有更優雅的方式來實現相同的目的?

你問的是如何拆分字符串。 Boost有一個有用的實用程序boost :: split()

http://www.boost.org/doc/libs/1_48_0/doc/html/string_algo/usage.html#id3115768

這是一個將結果單詞放入向量的示例:

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t "));
Code in c++
#include<sstream>
#include<vector>
using namespace std;    
string diskNames="vbbc anmnsa mansdmns";
string temp;
vector <string> cds;
stringstream s (diskNames);
while(s>> temp)
cds.push_back(temp);

使用流迭代器和標准函數:

static int myfunc(std::string const& stringInput)
{
    std::stringstream ss(stringInput);

    std::for_each(std::istream_iterator<std::string>(ss),
                  std::istream_iterator<std::string>(),
                  [&counters](std::string const& word) { ++counters[word];}
                 )
    ...
}

如果你沒有lambda那么:

struct Helper
{
     void operator()(std::string const& word) const {++counters[word];}
     Helper(CounterType& c) : counters(c) {}
     CounterType& counters;
};

static int myfunc(std::string const& stringInput)
{
    std::stringstream ss(stringInput);

    std::for_each(std::istream_iterator<std::string>(ss),
                  std::istream_iterator<std::string>(),
                  Helper(counters)
                 )
    ...
}

也許使用ostringstream

istringstream(stringInput); // initialize with the string

在Visual C ++ 11中,您可以使用TR1中的regex_token_iterator。

sregex_token_iterator::regex_type white_space_separators("[[:space:]]+",regex_constants::optimize);

for(sregex_token_iterator i(s.begin(),s.()end,white_space_separators,-1),end; i!=end; i++)
{
 cout << *i << endl;
 // or use i.start, i.end which is faster access
}

如果您擔心性能(以及字符串復制等開銷),您可以編寫自己的例程:

#include <ctype.h>

#include <string>
#include <iostream>
using namespace std;

int main()
{
 string s = "Text for tokenization  ";

 const char *start = s.c_str();
 const char *end = start + s.size();
 const char *token = start;

 while (start!=end)
 {
   if(isspace(*start))
   {
    if (token < start)
    {
      // Instead of constructing string, you can 
      // just use [token,start] part of the input buffer
      cout << string(token,start) << ' ';
    }

    start++;
    token = start;
   }
   else
   {
    start++;
   }
 } 

 if (token < start)
 {
    cout << string(token,start) << ' ';
 }

}

暫無
暫無

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

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