将一个字符串拆分成一个要再次调用的字数组

时间:2014-02-21 13:32:05

标签: java arrays string computer-science jgrasp

这是我目前的代码

import java.util.*;
import java.io.*;
public class USconstitution   
{
  public static void main(String [] args) throws Exception
  {
     Scanner inFile = new Scanner(new File("constitution.txt"));
     int x = 0;
     int keyword1 = 0;
     Scanner keyboard = new Scanner(System.in);
     System.out.println("Enter a word from the keyboard");
     String input = keyboard.next();
     while(inFile.hasNext())
     {
        String word = inFile.next();
        x++;
        if(input.equalsIgnoreCase(word))
           keyword1++;
     }
     //System.out.println("\n" + x);
     System.out.println("The constitution has " + x + " words");
     System.out.println("The first keyword shows up " + keyword1 + " times in the  

     constitution");
  }
}

输出如此 =

从键盘输入一个单词

会长

宪法有4610字

第一个关键字在宪法中出现了20次


我对这个程序的目标是搜索一个包含美国宪法的文本文件。

第一部分只是计算文本文件中有多少单词,我尝试做的下一位是允许人们搜索某些关键字并让它搜索文本文件并说出该单词出现的次数

我正在考虑提示询问用户希望输入哪些关键字,并让它使用split方法将每个单词创建为单个字符串,然后在文件中搜索该单词然后输出它出现的次数。虽然我不太确定如何解决这个问题,但我们将非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

试试这个:

public static void main(String[] args)
{       
    String text = "the quick brown fox jumps fox fox over the lazy dog brown";
    String[] textArray = text.split(" ");
    String[] keysToSearch = {"the", "fox", "dog"};
    int count = 0;
    System.out.println(text);

    for(String key: keysToSearch)
    {                       
        for(String s : textArray)
        {
            if(key.equals(s))
            {
                count++;
            }               
        }
        System.out.println("Count of ["+key+"] is : "+count);
        count=0;
    }
}

输出:

the quick brown fox jumps fox fox over the lazy dog brown
Count of [the] is : 2
Count of [fox] is : 3
Count of [dog] is : 1

答案 1 :(得分:0)

从主方法中获取检出的代码,并将其放在一个单独的方法中,该方法将一个关键字作为参数。然后,您可以使用

拆分从控制台给出的输入字符串
String[] keywords = input.split(" "); // will split at spaces

然后你要做的就是循环遍历数组中的所有关键字

for(int  i = 0; i < keywords.length; i++){

    yourCountMethod(keywords[i]);

}

这只是一般性的想法,显然你必须改变代码以适应。

希望有所帮助:)

相关问题