菜鸟问题:关于字符串

follow_suzhou 2004-10-27 12:55:36
从命令行接受一个串,打印出如下内容:单词个数;最长的长度;最短的长度;平均的长度

请问如何从字符串里面得到单词,和单词的长度?
...全文
55 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
tiger_shi 2004-10-27
  • 打赏
  • 举报
回复
可以考虑用String的方法
public String[] split(String regex)Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The string "boo:and:foo", for example, yields the following results with these expressions:

Regex Result
: { "boo", "and", "foo" }
o { "b", "", ":and:f" }


Parameters:
regex - the delimiting regular expression
Returns:
the array of strings computed by splitting this string around matches of the given regular expression
Throws:
PatternSyntaxException - if the regular expression's syntax is invalid
NullPointerException - if regex is null
Since:
1.4
See Also:
Pattern
边城狂人 2004-10-27
  • 打赏
  • 举报
回复
/*
* @(#) Test.java
* Create By James Fancy
*/
package jamesfancy;

public class Test {

public static void main(String[] args) {
String text = "Subject areas are optional but highly recommended for "
+ "models of twenty classes or more. The purpose of subject "
+ "areas is to provide a convenient aggregation of model "
+ "classes and to partition large models into smaller more "
+ "manageable subsets.\n"
+ "You could document following parts (for example, use case "
+ "model, class model, and interaction model) for every "
+ "subject areas, at the same time give a whole program "
+ "diagram and literary description.";
System.out.println(text);
String[] words = text.split("[,(). \t\n\r]{1,}");
int total = words.length;
int maxLength = 0;
int minLength = text.length();
int totalLength = 0;

for (int i = 0; i < total; ++i) {
System.out.println("[Word] " + words[i]);
int len = words[i].length();
if (maxLength < len) {
maxLength = len;
}
if (minLength > len) {
minLength = len;
}
totalLength += len;
}

System.out.println("单词总数:" + total);
System.out.println("最大长度:" + maxLength);
System.out.println("最小长度:" + minLength);
System.out.println("平均长度:" + (double) totalLength / total);
}

}
enrico 2004-10-27
  • 打赏
  • 举报
回复
public class Test {
public static void main(String[] args) {
int[] len = new int[args.length];

for (int i = 0; i < args.length; i++) {
len[i] = args[i].length();
System.out.println(len[i]);
}
}
}
like_this 2004-10-27
  • 打赏
  • 举报
回复
可以这样试试
单词可以以空格为分隔符依次截取为一个新的字符串
然后可以用.lenght来计算长度
边城狂人 2004-10-27
  • 打赏
  • 举报
回复
先用 String 的 split 方法把字符串拆开,然后再来计算和统计。
enrico 2004-10-27
  • 打赏
  • 举报
回复
直接取args的长度啊
tiger_shi 2004-10-27
  • 打赏
  • 举报
回复
以空格做分割符就可以了.
String[] result=source.split(" ");

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧