从字符拆分字符串

时间:2017-09-08 21:40:36

标签: c++ string split

我试图创建一个将字符串拆分为2D数组token[100][100]的程序。它会将整个字符串分成单独的单词,但每次遇到一段时间它应该token[i++][j]。到目前为止,我有这个。

#include <iostream>
#include <istream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
    string code;
    getline(cin, code);
    string codef[100];
    string token[100][100];
    int j = 0, i=0;
    for (i = 0; i < 2; i++) {
        stringstream ssin(code);
        while (ssin.good() && j < 4) {
            ssin >> token[i][j];
            ++j;
            if (token[i][j] == ".") {
                break;
            }
        }
    }

    for (i = 0; i < 4; i++) {
        for (j = 0; j < 4; j++) {
            cout << token[i][j] << endl;
        }
        cout << endl;
    }
    return 0;
}

我这样做的方法要求你在句号之前放置一个空格,因为它会检查单独的字符串,如果你把这段时间组合起来:&#34; hello。&#34;它显然没有认识到它。我不希望这种情况发生,是否有更好的方法使这项工作?现在我把字符串限制为只有2个句子和每个句子4个单词,包括句点,所以从技术上讲只有3个单词,然后是句号。

1 个答案:

答案 0 :(得分:1)

为什么不简单地使用std::string::find_first_of在普通的vanilla std :: string上搜索分隔符?当找不到任何内容时,它将返回std::string::npos。顺便说一句:我真的建议为std :: array或std :: vector删除那个好的旧数组。使用std :: vector可以摆脱那些糟糕的硬编码限制。

无论如何,这是我的建议。注意:我省略了对数组访问的限制检查,以便让您更容易阅读代码,要么迁移到vector并使用push_back,要么必须添加限制检查

我认为代码几乎是不言自明的,只有一句话:当我们找不到另一个分隔符时,需要if(pos > last_pos),因为pos == last_pos

#include <iostream>
#include <string>

int main()
{
    std::string code = "The quick brown fox jumps over the lazy dog. Lorem ipsum dolor. Cooky";

    std::string token[100][100];
    std::size_t last_pos = 0, pos;
    int sentence = 0, word = 0;
    while ((pos = code.find_first_of(". ", last_pos)) != std::string::npos)
    {
        if (pos > last_pos)
            token[sentence][word] = code.substr(last_pos, pos-last_pos /*length*/ );

        if(code.substr(pos, 1)[0] == '.')
        {
            ++sentence;
            word = 0;
        }
        else
            ++word;
        last_pos = pos+1;
    }
    if (last_pos < code.length())
        token[sentence][word] = code.substr(last_pos, std::string::npos);


    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
            std::cout << token[i][j] << std::endl;
        }
        std::cout << std::endl;
    }

    return 0;
}

由于你的硬编码限制,输出有点模糊,但这与字符串拆分无关,所以我把它保留原样:

The
quick
brown
fox


Lorem
ipsum
dolor


Cooky
相关问题