【问题标题】:Reading chunks of line from text file into strings将文本文件中的行块读入字符串
【发布时间】:2015-03-09 21:31:57
【问题描述】:

所以说如果我在文本文件中有这一行。

AarI/CACCTGCNNNN'NNNN/'NNNNNNNNGCAGGTG//

我想要的是将此行读入一个字符串,直到出现正斜杠,然后开始将下一组字符读入另一个字符串。所以在这个例子中,我将有 3 个字符串包含

string1 =  "AarI"
string2 = "CACCTGCNNNN'NNNN"
string3 = "'NNNNNNNNGCAGGTG"

知道该怎么做吗?

【问题讨论】:

  • 为什么不将整个字符串读入内存然后拆分呢?
  • 是的 - 坐下来写代码。我们不是代码编写服务。

标签: c++ string text ifstream


【解决方案1】:

istream::getline() 带有分隔符“/” - 请参阅:http://www.cplusplus.com/reference/istream/istream/getline/

不是最好的或最安全的,可能是最简单的方法之一。

【讨论】:

  • 最好将std::getline转换成字符串而不是使用C字符串。
  • 当然可以,然后在字符串缓冲区上使用.getline(..., '/')
  • 您可以使用std::getline,它使用分隔符直接读入std::string
  • 确实,毫无疑问,这将是最简单的。
【解决方案2】:

使用sstream。下面的代码显示了如何拆分字符串的示例。

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

vector<string> split(string str, char delimiter);

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

  string DNAstr = "AarI/CACCTGCNNNN'NNNN/'NNNNNNNNGCAGGTG//";
  vector<string> splittedlines = split(DNAstr, '/');

  for(int i = 0; i < splittedlines.size(); ++i)
    cout <<""<<splittedlines[i] << " \n";

  return 0;
} 


vector<string> split(string str, char delimiter) {
  vector<string> buffer;
  stringstream ss(str); 
  string tok;

  while(getline(ss, tok, delimiter)) {
    buffer.push_back(tok);
  }

  return buffer;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-30
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    相关资源
    最近更新 更多