c++ - 为什么 C++ 字符串分词器不工作

标签 c++ string tokenize

我试图用 C++ 编写一个简单的 std::string 分词器,但我无法让它正常工作。我在网上找到了一个确实有效的方法,并且我明白它为什么有效....但我仍然不明白为什么我原来的那个有效。我假设它是我遗漏的一些愚蠢的小东西......我很感激指向正确方向的指针;谢谢!

输入(随机字符和带“\n”“\t”的符号):

"This is a test string;23248h> w chars, aNn, 8132; ai3v2< 8&G,\nnewline7iuf32\t2f,f3rgb, 43q\nefhfh\nu2hef, wew; wg"

分词器:

size_t loc, prevLoc = 0;
while( (int)(loc = theStr.find_first_of("\n", prevLoc) ) > 0) {
    string subStr = theStr.substr(prevLoc, loc-1);        // -1 to skip the \n
    cout << "SUBSTR: '" << subStr << "'" << endl << endl;
    tokenizedStr->push_back( subStr );
    prevLoc = loc+1;
} // while

输出:

SUBSTR: 'This is a test string;23248h> w chars, aNn, 8132; ai3v2< 8&G'

SUBSTR: 'newline7iuf32  2f,f3rgb, 43q
efhfh
u2hef, wew; wg'

SUBSTR: 'efhfh
u2hef, wew; wg'

注意第二个“SUBSTR”(显然)仍然有换行符(“\n”)

可编译代码:

#include <vector.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>

using namespace std;

int main(int argc, char *argv[]) {

    string testStr = "This is a test string;23248h> w chars, aNn, 8132; ai3v2< 8&G,\nnewline7iuf32\t2f,f3rgb, 43q\nefhfh\nu2hef, wew; wg";
    vector<string> tokenizedStr;

    size_t loc, prevLoc = 0;
    while( (int)(loc = testStr.find_first_of("\n", prevLoc) ) > 0) {
        string subStr = testStr.substr(prevLoc, loc-1);        // -1 to skip the \n                                                                                                     
        cout << "SUBSTR: '" << subStr << "'" << endl << endl;
        tokenizedStr.push_back( subStr );
        prevLoc = loc+1;
    } // while                                                                                                                                                                        

    return 0;
}

最佳答案

substr 的第二个参数是大小,而不是位置。而不是这样调用它:

testStr.substr(prevLoc, loc-1);

试试这个:

testStr.substr(prevLoc, loc-prevLoc);

一旦你解决了这个问题,你将遇到的下一个问题是你没有打印最后一个子字符串,因为一旦你找不到换行符就停止了。所以从最后一个换行符到字符串的末尾不会被存储。

关于c++ - 为什么 C++ 字符串分词器不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8650648/

相关文章:

c++ - 如何初始化 C 字符串数组(无 STL)

python - python中的字符串替换性能

php - 突出显示一段带有匹配文本的 HTML 代码

elasticsearch 将 "H&R Blocks"标记为 "H"、 "R"、 "H&R"、 "Blocks"

c++ - 试图标记一个字符串

c++ - qt slider 问题c++

c++ - 是否有将 EBNF 翻译成 boost::spirit 的翻译工具?

java - 使用分隔符 ". "标记 Java 中的问题

c++ - 为什么 QVector 的迭代器内部使用前缀增加而后缀减少?

c - 如何将 strcpy() 与数组元素一起使用?