首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

怎样一个单词一个单词的输出?该如何解决

2012-02-07 
怎样一个单词一个单词的输出?importjava.util.*classExample{publicstaticvoidmain(Stringargs[]){String

怎样一个单词一个单词的输出?
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);

}
}
大虾帮我改下

[解决办法]
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);
}
}
[解决办法]
按你要求可以把你的程序修改如下:
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+ "个 ");

}
}

热点排行