比较文件中的字符串

时间:2016-11-05 11:14:04

标签: c++ string file compare

我在文本文件中给出了一列字符串,我必须将它们相互比较 - 我想将第一个字符串与其下面的所有字符串进行比较,然后返回第二个字符串并将其与下面的所有字符串进行比较等等。问题是我不知道如何为它编写代码

2 个答案:

答案 0 :(得分:1)

使用嵌套循环可以达到预期效果;

#include <iostream>
#include <fstream>
#include <vector> //include this to use vector

using namespace std;

int main() {

    //to take input from the file
    ifstream fin;

    //to read the same strings into 2 arrays so we can loop it appropriately
    //by taking one string and comparing it to all below it.
    vector <string> line1;
    vector <string> line2;

    //to hold a line of string
    string temp;

    //replace this with with your file 
    fin.open("hello.txt");

    //to check if file cannot be opened or does not exist
    if(!fin.is_open()) {
        cout << "file could not be opened";
    }

    //strings are inserted into element of these 2 vectors 
    //(Internally, vectors use a dynamically allocated array to store their elements in adjacent memory locations)
    //that is why i decided to use vectors. Also, using the push_back method
    //to insert the strings into both arrays means we don't have to specify the size of the array
    while (getline(fin, temp)) {
        line1.push_back(temp);
        line2.push_back(temp);
    }


    //nested loop is used to make sure one string is used to operate 
    //on all the strings in the file and move to the next to do same
    //and so on...
    for (unsigned int i = 0; i < line1.size(); i++) {
        for (unsigned int j = 0; j < line2.size(); j++) {
            //you can compare first string with all below here however you want to do it
            //I just did this so you see how it behaves
            cout << line1[i] << " = " << line2[j] << endl;
        }
    }

    return 0;
}

答案 1 :(得分:0)

最简单的方法是使用cmd linux就像grep:

// 1路

 grep -w -v -f file1.log file.2 > mach.log

// 2路

grep -w -f file1.log file.2 > mach.log

你不能忘记旗帜的意思:

-w, - word-regexp               仅选择包含构成整个单词的匹配项的行。测试是匹配的子字符串必须位于行的开头,或者前面是非单词构成字符。               同样,它必须位于行的末尾或后跟非单词构成字符。单词构成字符是字母,数字和下划线。

-v, - 反转匹配               反转匹配感,选择不匹配的行。

-f FILE, - file = FILE               从FILE获取模式,每行一个。如果多次使用此选项或与-e(--regexp)选项组合使用,请搜索给定的所有模式。空文件包含零模式,和               因此没有任何匹配。