1

假设文本文件包含:

他是个男孩 。
她生病了 。
阿里在玩。
我们正在吃 。
狗乱叫 。
他和他的兄弟正在奔跑。
他在玩。

我想通过单独比较字符串如下:

他是
一个
男孩
男孩。


了。

等等。

我已经把上面所有的词都放到了一个向量中。如何与我输入的字符串进行比较?

假设方式是这样的: 输入字符串:He is a boy .

He is从输入字符串中,并希望通过找出它在向量中出现的次数来与向量进行比较。

这是我尝试过的:

try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");

    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    int lineNum = 0;

    Vector text= new Vector();
    Enumeration vtext = text.elements();

    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
        // Print the content on the console
        //System.out.println (strLine);
        lineNum++;

        String[] words = strLine.split("\\s+");

        //System.out.println(words[0]);
        for (int i = 0, l = words.length; i + 1 < l; i++){
            text.addElement(words[i] + " " + words[i + 1]);
        }       
    }
    String str23 = "She is"; 
    while(vtext.hasMoreElements()){
        String yy = "He is";
        if(text.contains(yy)){
            System.out.println("Vector contains 3."); 
        }
        System.out.print(vtext.nextElement() + " "); 
        System.out.println(); 
    }       
    System.out.println(text);
    System.out.println(lineNum);

    //Close the input stream
    in.close();
}catch (Exception e){  //Catch exception if any
    System.err.println("Error: " + e.getMessage());
}
4

1 回答 1

0

这可能是浪费时间来回答 - 但这里是:

我将您的循环更改为:

String str23 = "She is"; 
int countOfHeIs = 0;
String yy = "He is";
while(vtext.hasMoreElements()){

    if (vtext.nextElement().equals(yy))
    {
        countOfHeIs++;
    }
    if(text.contains(yy)){
        System.out.println("Vector contains 3."); 
    }
    System.out.print(vtext.nextElement() + " "); 
    System.out.println(); 
}       
System.out.println(text);
System.out.println(lineNum);
System.out.printf("'%s' appears %d times\n", yy, countOfHeIs);

该方法contains不计算出场次数——它只会给你一个是/否的指示——你应该自己计算出场次数。

这不是您问题的最佳解决方案 - 因为 aVector不是这里的最佳选择。我建议使用 aMap<String,Integer>来跟踪每个字符串的出现次数。

于 2012-10-03T09:49:32.550 回答