java - 如何使用 vector Java比较我输入的字符串和文本文件中的字符串?

标签 java string vector

假设文本文件包含:

He is a boy .
She is sick .
Ali is playing .
We are eating .
The dog is barking .
He and his brother are running .
He is playing .

我想通过分隔比较字符串如下:

He is
is a
a boy
boy .
She is
is sick
sick .

等等。

我已将上面所有的单词放入一个 vector 中。如何与我输入的字符串进行比较?

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

他来自输入字符串,想要与 vector 进行比较,找出它在 vector 中出现的次数。

这是我尝试过的:

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());
}

最佳答案

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

我将你的循环更改为:

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>跟踪每个字符串出现的次数。

关于java - 如何使用 vector Java比较我输入的字符串和文本文件中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11383852/

相关文章:

c++ - 运行 mastermind 程序时出现 Cygwin 错误

java - 带有进度对话框android的泄漏窗口错误

Java 对象是我类(class)的 super 对象吗?

java - Android 在 webview 上进行地理定位

string - BASH 中的意外文件结尾

c++ - 处理包含动态分配成员的对象的 vector

java - 在 Android 中创建并连接到 SQLite DB

java - 结束字符串、递归和搜索事件

java - 如何创建一个循环将堆栈放入 string[] 中?

c++ - 为什么成对 vector 不存储输入?