使用StringTokenizer计算单词中的单词和字符数

时间:2013-05-24 00:39:34

标签: java string token stringtokenizer

目标是从用户输入句子,对其进行标记,然后仅提供有关前三个单词的信息(单词本身,长度,然后平均前3个单词长度)。我不知道如何将令牌变成字符串。我只需要一些指导 - 不知道如何继续。到目前为止我已经有了这个:

public static void main(String[] args) {

    String delim = " ";

    String inSentence = JOptionPane.showInputDialog("Please enter a sentence of three or more words: ");

    StringTokenizer tk = new StringTokenizer(inSentence, delim);

    int sentenceCount = tk.countTokens();


    // Output
    String out = "";
    out = out + "Total number of words in the sentence: " +sentenceCount +"\n";

    JOptionPane.showMessageDialog(null, out);


}

我真的很感激任何指导!

3 个答案:

答案 0 :(得分:1)

如果您只想获得前3个代币,那么您可以这样做:

String first = tk.nextToken();
String second = tk.hasMoreTokens() ? tk.nextToken() : "";
String third = tk.hasMoreTokens() ? tk.nextToken() : "";

从那里应该很容易计算其他要求

答案 1 :(得分:1)

public static void main(String[] args) {

    String delim = " ";

    String inSentence = JOptionPane.showInputDialog("Please enter a sentence of three or more words: ");

    StringTokenizer tk = new StringTokenizer(inSentence, delim);

    int sentenceCount = tk.countTokens();

    // Output
    String out = "";
    out = out + "Total number of words in the sentence: " +sentenceCount +"\n";

    JOptionPane.showMessageDialog(null, out);

    int totalLength = 0;
    while(tk.hasMoreTokens()){
        String token = tk.nextToken();
        totalLength+= token.length();
        out = "Word: " + token + " Length:" + token.length();
        JOptionPane.showMessageDialog(null, out);
    }

    out = "Average word Length = " + (totalLength/3);
    JOptionPane.showMessageDialog(null, out);
}

答案 2 :(得分:0)

使用nextToken()获取单个字符串的方法。

while (tk.hasMoreTokens()) {
  System.out.println(st.nextToken());
}

当然,除了打印它们外,您还可以做任何其他事情。如果您只想要三个第一个令牌,则可能不希望使用while循环,而是使用几个简单的if语句。