我试图用 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/