我有一个从第三方收到的字符串.此字符串实际上是文本文件中的文本,它可能包含用于行终止的UNIX LF或Windows CRLF.如何将其分解为多个字符串而忽略空行?我打算做以下事情,但不确定是否有更好的方法.我需要做的就是逐行阅读.这里的矢量只是一个方便,我可以避免它. *不幸的是我无法访问实际文件.我只收到字符串对象*
string textLine;
vector<string> tokens;
size_t pos = 0;
while( true ) {
size_t nextPos = textLine.find( pos, '\n\r' );
if( nextPos == textLine.npos )
break;
tokens.push_back( string( textLine.substr( pos, nextPos - pos ) ) );
pos = nextPos + 1;
}
Run Code Online (Sandbox Code Playgroud)
您可以std::getline在阅读文件时使用,而不是将整个内容读入字符串.这将默认逐行破坏.你可以简单地不推送任何空的字符串.
string line;
vector<string> tokens;
while (getline(file, line))
{
if (!line.empty()) tokens.push_back(line);
}
Run Code Online (Sandbox Code Playgroud)
更新:
如果您无权访问该文件,则可以通过使用stringstream整个文本初始化来使用相同的代码. std::getline适用于所有流类型,而不仅仅是文件.
我将使用 getline 基于 \n 创建新字符串,然后操作行结尾。
string textLine;
vector<string> tokens;
istringstream sTextLine;
string line;
while(getline(sTextLine, line)) {
if(line.empty()) continue;
if(line[line.size()-1] == '\r') line.resize(line.size()-1);
if(line.empty()) continue;
tokens.push_back(line);
}
Run Code Online (Sandbox Code Playgroud)
编辑:使用istringstream而不是stringstream.