c++ - 在文件中搜索字符串(逐行),忽略单词之间空格的大小

标签 c++ string file-io

我是 C++ 的初学者,所以请理解...

我想在文件 (haystack) 中搜索字符串 (needle),方法是分别读取每一行,然后在该行中搜索 needle。然而,理想情况下,对于更健壮的代码,我希望能够只读取行中的单个单词,这样如果单词之间有更大的(即多个)空白间隙,它们在搜索针时将被忽略。 (例如,也许使用 >> 运算符??)也就是说,针串不必与文件中单词之间的空格大小完全匹配。

例如,如果我有针:

"The quick brown fox jumps over the lazy dog" 

在文件中,这可能被写成(在特定行上):

... "The quick brown      fox jumps over the        lazy dog" ...

有没有一种有效的方法来做到这一点?

目前,我在我的针串中包含了必要数量的空格,但如果可能的话,我想改进代码。

我的代码目前看起来像下面这样(在类的方法中):

double var1, var2;
char skip[5];
std::fstream haystack ("filename");
std::string needle = "This is a string, and var1    =";
std::string line;
int pos;
bool found = false;

// Search for needle
while ( !found && getline (haystack,line) ) {
  pos = line.find(needle);  // find position of needle in current line

  if (pos != std::string::npos) { // current line contains needle

      std::stringstream lineStream(line);
      lineStream.seekg (pos + needle.length());
      lineStream >> var1;
      lineStream >> skip;
      lineStream >> var2;
      found = true;
  }
}

(为清楚起见,在找到字符串(针)后我想存储该行的下一个单词,或者在某些情况下存储下一个单词,然后跳过一个单词并存储以下单词,例如:

有一个文件:

... ...
... This is a string, and var1    = 111 and 777 ...
... ...

我想提取 var1 = 111; var2 = 777; )

在此先感谢您的帮助!

最佳答案

这会起作用,尽管我认为有更短的解决方案:

std::size_t myfind(std::string ins, std::string str) {
  for(std::string::iterator it = ins.begin(), mi = str.begin(); it != ins.end(); ++it) {
    if(*it == *mi) {
      ++mi;
      if (mi == str.end())
        return std::distance(ins.begin(),it);
    }
    else {
      if(*it == ' ')
        continue;
      mi = str.begin();
    }
  }
  return std::string::npos;
}
// use:
myfind("foo The quick brown      fox jumps over the        lazy dog bar", "The quick brown fox");

关于c++ - 在文件中搜索字符串(逐行),忽略单词之间空格的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8598697/

相关文章:

c - 在 Linux 上使用 fgets() 读取带有 DOS 行结尾的文件

c++ - 如何获取所有可用的事件日志名称?

c++ - 从 boost multi_index 数组中 move 元素

c++ - 来自函数模板的显式模板特化不起作用

java - 如何在引号之间输出字符串(在控制台中)?

java - 字符串与另一个字符串重叠

C++ 浮点截断和设置精度逻辑错误

c++ - 访问冲突写入位置未处理的异常

C 字符串、指针、Put

perl - 集群:用sysopen截断的正确方法