将长字符串分成多个c ++

问题描述

| 我有一个从第三方收到的字符串。该字符串实际上是文本文件中的文本,它可能包含用于行终止的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;
}
    

解决方法

我会使用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);
}
编辑:使用
istringstream
代替
stringstream
。     ,从文件中读取内容时,可以使用
std::getline
,而不是将整个内容读取为字符串。默认情况下,这将逐行分解。您根本不能push_back任何出现为空的字符串。
string line;
vector<string> tokens;

while (getline(file,line))
{
    if (!line.empty()) tokens.push_back(line);
}
更新: 如果您无权访问该文件,则可以通过在整个文本中初始化一个ѭ3use来使用相同的代码。
std::getline
适用于所有流类型,而不仅仅是文件。     ,我将使用此处给出的方法(std :: istringstream上的std :: getline)... 使用令牌拆分C ++ std :: string,例如“;” ...省略std :: getline的\'; \'参数。     ,在很大程度上取决于您的工具包中已经存在的内容。我工作很多 来自Windows并在Unix下读取的文件,反之 反之亦然,所以我掌握了大多数将CRLF转换为LF的工具。 如果您没有任何功能,则可能需要以下功能:
void addLine( std::vector<std::string>& dest,std::string line )
{
    if ( !line.empty() && *(line.end() - 1) == \'\\r\' ) {
        line.erase( line.end() - 1 );
    }
    if ( !line.empty() ) {
        dest.push_back( line );
    }
}
做你的插入。至于将原始文本分成几行, 您可以像其他人一样使用
std::istringstream
和as4ѭ 建议即使简单,它也很简单明了。 (The9是一个相当沉重的机制,因为它支持 您不需要的各种输入转换。)或者,您 可能会考虑以下方面的循环:
std::string::const_iterator start = textLine.begin();
std::string::const_iterator end   = textLine.end();
std::string::const_iterator next  = std::find( start,end,\'\\n\' );
while ( next != end ) {
    addLine( tokens,std::string( start,next ) );
    start = next + 1;
    next = std::find( start,\'\\n\' );
}
addLine( tokens,end ) );
或者,您可以将事情分解为单独的操作:
textLine.erase(
    std::remove( textLine.begin(),textLine.end(),\'\\r\'),textLine.end() );
摆脱所有CR,
std::vector<std:;string> tokens( split( textLine,\'\\n\' ) );
,分成几行,其中
split
是广义函数 遵循以上循环的思路(一种有用的工具,可以添加到您的 工具包),最后:
tokens.erase(
    std::remove_if( tokens.begin(),tokens.end(),boost::bind( &std::string::empty,_1 ) ),tokens.end() );
。 (通常:如果是一种情况,请使用 基于9ѭ的解决方案。如果您认为您可能需要做 以后可能会不时添加类似的内容add15ѭ 即可使用并使用它。)     ,您可以使用strtok。   将字符串拆分为令牌      对该函数的调用序列   将str拆分为令牌,这些令牌是   连续字符序列   由任何字符分隔   是分隔符的一部分。     ,我会将字符串放入stringstream中,然后像前面提到的答案一样使用getline方法。然后,您可以像真正从另一个字符串读取文件时一样从文件中读取文本。