怎样一个单词一个单词的输出?

sjshuang 2007-03-04 04:16:45
import java.util.*;
class Example
{
public static void main(String args[])
{
String s=new String("we,go,to,shchool,yeah");
StringTokenizer token=new StringTokenizer(s,",");
int n=token.countTokens();
String word=token.nextToken();
System.out.printf("%s,%d",word,n);

}
}
大虾帮我改下
...全文
345 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
nowitzki41 2007-03-05
  • 打赏
  • 举报
回复
talent_marquis(甜菜侯爵)的好
talent_marquis 2007-03-04
  • 打赏
  • 举报
回复
还有一点疑惑
String word : words
这个“:”代表什么意思啊?
谢谢....

啊,这个是SDK1.5新增添的Foreach功能
说白了就是让for循环更容易罢了
for(String word : words) 这句话如果翻译成中文,实际上的含义是
“建立一个String的实例word,让它遍历String数组words中所有的元素”
这个":"你可以理解为“遍历”的意思,这样以后读程序就方便理解多了
talent_marquis 2007-03-04
  • 打赏
  • 举报
回复
补充说明:

for(String word : words)
{
System.out.println(word);
}

等效于:

for(int i = 0 ; i<words.length; i++)
{
System.out.println(words[i]);
}
duanxin929 2007-03-04
  • 打赏
  • 举报
回复
按你要求可以把你的程序修改如下:
import java.util.*;
class Example
{
public static void main(String args[])
{
String s=new String("we,go,to,shchool,yeah");
StringTokenizer token=new StringTokenizer(s,",");
int n=token.countTokens();
while(token.hasMoreTokens())
{
String word=token.nextToken();
System.out.println(word);
}
System.out.println("共有单词:"+n+"个");

}
}
talent_marquis 2007-03-04
  • 打赏
  • 举报
回复
StringTokenizer 是出于兼容性的原因而被保留的遗留类(虽然在新代码中并不鼓励使用它)。建议所有寻求此功能的人使用 String 的 split 方法或 java.util.regex 包。

下面的示例阐明了如何使用 String.split 方法将字符串分解为基本标记:

String[] result = "this is a test".split("\\s");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);

对于你的代码,最佳方法是
public static void main(String args[])
{
String s=new String("we,go,to,shchool,yeah");

String words[] = s.split(",");

for(String word : words)
{
System.out.println(word);
}
}
suihu 2007-03-04
  • 打赏
  • 举报
回复
用数组实现。
捏造的信仰 2007-03-04
  • 打赏
  • 举报
回复
System.out.println(s.replace(",", " "));

62,629

社区成员

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

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