找到子串c ++

时间:2010-08-10 09:55:29

标签: c++

  

可能重复:
  How to split a string?

您好,

我有一个字符串说“1,0,1”,我怎么能用逗号运算符分隔子字符串。

3 个答案:

答案 0 :(得分:2)

C ++没有用于完成此操作的内置函数。但是,可以使用std::string::find_first_of成员函数或非成员std::find来实现。

以下是使用后者的示例:

#include <string>
#include <vector>
#include <algorithm>


// given a string str, split it on every occurrence of the character delim
std::vector<std::string> tokenize(std::string str, char delim) {
    // store the results in a vector of strings
    std::vector<std::string> tokens;

    std::string::iterator end = str.end();
    std::string::iterator left = str.begin();
    for (;;) {
        // find the next occurrence of the delimiter
        std::string::iterator right = std::find(left, end, delim);
        // create a string from the end of last one up until the one we just foun
        tokens.push_back(std::string(left, right));
        // if we reached the end of the string, exit the loop
        if (right == end) { break; }
        // otherwise, start the next iteration just past the delimiter we just found
        left = right + 1;
    }
    return tokens;
}

// test program
int main() {
    std::string str = "foo, bar, baz";
    std::string str2 = "foo, bar, baz,";
    std::string str3 = "foo";
    std::string str4 = "";
    std::string str5 = ",";

    std::vector<std::string> tokens = tokenize(str, ',');
    std::vector<std::string> tokens2 = tokenize(str2, ',');
    std::vector<std::string> tokens3 = tokenize(str3, ',');
    std::vector<std::string> tokens4 = tokenize(str4, ',');
    std::vector<std::string> tokens5 = tokenize(str5, ',');
}

当然要处理很多边界情况,这种实现可能不会完全符合您的要求,但它应该为您提供一个起点。

答案 1 :(得分:0)

另一种方法是使用strtok。这是一种古老的方式,但它仍然适用于这个问题。

using <vector>
using <string>

char* token, line[512];
std::string tokenStr;
std::string lineStr = "0, 1, 2";
std::vector<std::string> commaSplit;
strcpy ( line, lineStr.c_str());

//Remove spaces and find the first instance of ','
token = strtok( line, " ," );
while(token != NULL)
{
    //Copy the token to a string
    tokenStr = token;

    //Add the token to the vector
    commaSplit.push_back(token);

    //Find next instance of the ,
    token = strtok(NULL, " ,");
}

答案 2 :(得分:-1)

在Google搜索爆炸标记化字符串的算法。这很简单。

您还可以查看文档并使用可用工具:http://www.cplusplus.com/reference/string/string/

一个简单的实现可能是:

void tokenize(const string & text, vector<string> & tokens, char delim)
{
  size_t length = text.size();
  string token = "";

  for(size_t i=0;i<length;i++)
  {
      if(text[i] != delim)
      {
        token += text[i];
      }
      else
      {
        if(token.size() > 0)
        {
          tokens.push_back(token);
        }
        token = "";
      }
  }
  tokens.push_back(token);
}