在文本文件中搜索字符串

时间:2015-06-16 09:36:53

标签: c++ c string text

假设你有一个像这样的文本文件

您希望文本中的所有内容都是" 尺寸值"

但是用不同的值重复了那么多时间

"field_pic_flag : 0 
bottom_field_flag : 0 
idr_pic_id : 0 
Found NAL at offset  ,size 28813  !! Found NAL"

"field_pic_flag : 0 
bottom_field_flag : 0 
idr_pic_id : 0 
Found NAL at offset  ,size 210  !! Found NAL"

结果 我只想要一个代码来编写一个这种格式的文本文件,如下所示

size 28813 size 210 and so on

2 个答案:

答案 0 :(得分:1)

如果使用C / C ++不是强制性的,那么grep可能是你的朋友:

grep "size [0-9]*" -o yourfile.txt > all_sizes.txt

如果你只需要50个第一个结果,head就是:

head -n 50 all_sizes > result.txt

(现在,假设您正在使用某种Unix或OS X ......)

答案 1 :(得分:0)

我看到这个问题被标记为C / C ++。如果您被允许使用C ++ 11,那么您可以轻松使用新引入的正则表达式库。

在下面的代码中,数据直接存储在字符串中,但您可以轻松地从文件中读取数据。结果保存在result.txt文件中,同时显示在屏幕上。

#include <iostream>
#include <string>
#include <regex> // The new library introduced in C++ 11
#include <fstream>

int main()
{
    const int n = 50;
    int i = 0;

    std::ofstream outputFile;
    outputFile.open("result.txt");

    // You can read this string from your input file
    std::string s("\"field_pic_flag : 0\
        bottom_field_flag : 0\
        idr_pic_id : 0\
        Found NAL at offset, size 28813  !!Found NAL\"\
        \"field_pic_flag : 0\
        bottom_field_flag : 0\
        idr_pic_id : 0\
        Found NAL at offset, size 210  !!Found NAL\"");
    std::smatch m;
    std::regex e("size [0-9]*");   

    while (std::regex_search(s, m, e) && i++<n) {
        for (auto x : m) {
            std::cout << x << " ";
            outputFile << x << " ";
        }
        std::cout << std::endl;
        outputFile << std::endl;
        s = m.suffix().str();
    }

    outputFile.close();

    return 0;
}

经典解决方案需要更多努力。