2012-07-08 83 views
1

假设文本文件包含:如何比较输入的字符串并使用矢量Java比较文本文件中的字符串?

他是个男孩。
她生病了。
阿里在玩。
我们在吃东西。
这只狗在吠叫。
他和他的兄弟正在跑步。
他在玩。

而且我想通过单独的字符串比较到下面:



一个男孩
男孩。
她是
生病
生病了。

等等。

我已经把上面的所有单词放入一个向量中。我怎样才能比较我输入的字符串?

假设的方法是这样的: 输入字符串: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()); 
} 
+1

你有什么试过?另外,如果这是家庭作业,你应该添加正确的标签。 – 2012-07-08 14:24:27

+1

[*您尝试过什么?*](http://mattgemmell.com/2008/12/08/what-have-you-tried/) – 2012-07-08 14:25:11

+1

注意:'Vector'通常不是最好的列表类使用这些日子,因为它通常不需要同步。您可能应该使用“ArrayList”或“LinkedList”。 – Wyzard 2012-07-08 14:30:03

回答

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不包括外观 - 它只给你一个是/否的指示 - 你应该自己计算外观的数量。

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