编写一程序输出一个由若干单词构成的字符串中的最长单词及其长度,若字符串中有多个单词满足条件须将这些单词全部输出,要求给出该程序的N-S盒图。(注:程序书写要规范)
例:输入字符串为“The indictment said the defendants had collected geographical data indicating thousands of people would be killed in the chemical blast”
输出结果
最长单词:geographical
单词长度:12
例:输入字符串为“The indictment said the defendants had collected geographical data indicating thousands of people would be killed in the chemical blast”
输出结果
最长单词:geographical
单词长度:12
先调用String 的split(),把每个单词放到一个数组当中
然后再比较每个单词的长度,把最长的输出就可以了
//分析string,得到单词列表,并得到所有单词中最长单词的长度
List list = new LinkedList();
Node node = null;
Node maxNode = new Node();
StringBuffer wordBuffer = new StringBuffer();
String word = null;
for (int i = 0; i < string.length(); i++) {
char ch = string.charAt(i);
if (ch == ' ') { //为间隔字符,如空格和标点符号等
if (wordBuffer.length() != 0) {
word = wordBuffer.toString();
node = new Node(word, word.length());
list.add(node);
if (node.length > maxNode.length) {
maxNode = node;
}
wordBuffer.setLength(0);
}
} else {
wordBuffer.append(ch);
}
}
//添加最后一个单词
if (wordBuffer.length() != 0) {
word = wordBuffer.toString();
node = new Node(word, word.length());
list.add(node);
if (node.length > maxNode.length) {
maxNode = node;
}
wordBuffer.setLength(0);
}int max_length = maxNode.length;
System.out.println("Max Length: " + max_length);//输出最长的那几个单词
for (Iterator itr = list.iterator(); itr.hasNext();) {
node = (Node) itr.next();
if (node.length == max_length) {
System.out.println(node.string);
}
}
public String string = "";
public int length = 0;public Node(String string, int length) {
this.string = string;
this.length = length;
}public Node() {
this("", 0);
}
}