java 使用 StringTokenizer 统计单词中的单词数和字符数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16726121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use StringTokenizer to count number of words and characters in words
提问by Smeaux
The objective is to get a sentence input from the user, tokenize it, and then give information about the first three words only (word itself, length, and then average the first 3 word lengths). I'm not sure how to turn the tokens into strings. I just need some guidance - not sure how to proceed. I've got this so far:
目标是获取用户输入的句子,对其进行标记,然后仅给出前三个单词的信息(单词本身、长度,然后平均前 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);
}
I'd really appreciate any guidance!
我真的很感激任何指导!
采纳答案by cmbaxter
If you just wanted to get the first 3 tokens, then you could do something like this:
如果您只想获得前 3 个令牌,那么您可以执行以下操作:
String first = tk.nextToken();
String second = tk.hasMoreTokens() ? tk.nextToken() : "";
String third = tk.hasMoreTokens() ? tk.nextToken() : "";
From there should be pretty easy to calculate the other requirements
从那里应该很容易计算其他要求
回答by Kevin Bowersox
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);
}
回答by Victor Sand
The way to get the individual strings by using nextToken()
.
使用nextToken()
.
while (tk.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You're free to do anything else than printing them, of course. If you only want the three first tokens, you might not want to use a while
loop but a couple of simple if
statements.
当然,你可以自由地做任何事情,而不是打印它们。如果您只需要前三个标记,您可能不想使用while
循环而是使用几个简单的if
语句。