首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过分隔符将字符串拆分为数组?

如何通过分隔符将字符串拆分为数组?
EN

Stack Overflow用户
提问于 2009-05-20 20:48:22
回答 12查看 69K关注 0票数 14

我对编程很陌生。我一直试图用C++编写一个函数,该函数在给定参数下将字符串的内容爆炸到字符串数组中,例如:

代码语言:javascript
复制
string str = "___this_ is__ th_e str__ing we__ will use__";

应该返回字符串数组:

代码语言:javascript
复制
cout << stringArray[0]; // 'this'
cout << stringArray[1]; // ' is'
cout << stringArray[2]; // ' th'
cout << stringArray[3]; // 'e str'
cout << stringArray[4]; // 'ing we'
cout << stringArray[5]; // ' will use'

我可以很好地标记字符串,但对我来说最困难的部分是如何在分配当前字符串之前指定stringArray中的元素数,以及如何从函数中返回stringArray。

有人能教我怎么写这个函数吗?

Edit1: --我不一定需要将结果放在字符串数组中,只要有某种索引就可以作为常规变量调用任何容器。

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2009-05-20 21:00:33

这是我第一次尝试使用向量和字符串:

代码语言:javascript
复制
vector<string> explode(const string& str, const char& ch) {
    string next;
    vector<string> result;

    // For each character in the string
    for (string::const_iterator it = str.begin(); it != str.end(); it++) {
        // If we've hit the terminal character
        if (*it == ch) {
            // If we have some characters accumulated
            if (!next.empty()) {
                // Add them to the result vector
                result.push_back(next);
                next.clear();
            }
        } else {
            // Accumulate the next character into the sequence
            next += *it;
        }
    }
    if (!next.empty())
         result.push_back(next);
    return result;
}

希望这能让你对如何做这件事有一些想法。在示例字符串中,它使用以下测试代码返回正确的结果:

代码语言:javascript
复制
int main (int, char const **) {
    std::string blah = "___this_ is__ th_e str__ing we__ will use__";
    std::vector<std::string> result = explode(blah, '_');

    for (size_t i = 0; i < result.size(); i++) {
        cout << "\"" << result[i] << "\"" << endl;
    }
    return 0;
}
票数 15
EN

Stack Overflow用户

发布于 2009-05-20 22:09:06

使用STL (抱歉没有编译器测试)

代码语言:javascript
复制
#include <vector>
#include <string>
#include <sstream>

int main()
{
    std::vector<std::string>   result;

    std::string str = "___this_ is__ th_e str__ing we__ will use__";

    std::stringstream  data(str);

    std::string line;
    while(std::getline(data,line,'_'))
    {
        result.push_back(line); // Note: You may get a couple of blank lines
                                // When multiple underscores are beside each other.
    }
}

//或定义令牌

代码语言:javascript
复制
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
#include <sstream>

struct Token: public std::string  // Yes I know this is nasty.
{                                 // But it is just to demosntrate the principle.    
};

std::istream& operator>>(std::istream& s,Token& t)
{
    std::getline(s,t,'_');
   
    // *** 
    // Remove extra '_' characters from the stream.
    char c;
    while(s && ((c = s.get()) != '_')) {/*Do Nothing*/}
    if (s)
    {
        s.unget(); // Put back the last char as it is not '_'
    }
    return s;
}

int main()
{   

    std::string str = "___this_ is__ th_e str__ing we__ will use__";

    std::stringstream  data(str);

    std::vector<std::string>   result(std::istream_iterator<Token>(data),
                                      std::istream_iterator<Token>());
}
票数 11
EN

Stack Overflow用户

发布于 2012-11-26 00:50:44

它适用于我:

代码语言:javascript
复制
#include <iostream>
#include <vector>
#include <string>

using namespace std;

vector<string> explode( const string &delimiter, const string &explodeme);

int main(int argc, char *argv[])
{
    string str = "I have a lovely bunch of cocoa nuts";
    cout<<str<<endl;
    vector<string> v = explode(" ", str);
    for(int i=0; i<v.size(); i++)
        cout <<i << " ["<< v[i] <<"] " <<endl;
}

vector<string> explode( const string &delimiter, const string &str)
{
    vector<string> arr;

    int strleng = str.length();
    int delleng = delimiter.length();
    if (delleng==0)
        return arr;//no change

    int i=0;
    int k=0;
    while( i<strleng )
    {
        int j=0;
        while (i+j<strleng && j<delleng && str[i+j]==delimiter[j])
            j++;
        if (j==delleng)//found delimiter
        {
            arr.push_back(  str.substr(k, i-k) );
            i+=delleng;
            k=i;
        }
        else
        {
            i++;
        }
    }
    arr.push_back(  str.substr(k, i-k) );
    return arr;
}

来源: http://www.zedwood.com/article/106/cpp-explode-function

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/890164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档