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);

}
}
大虾帮我改下

解决方案 »

  1.   

    System.out.println(s.replace(",", " "));
      

  2.   

    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);
    }
    }
      

  3.   

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

  4.   

    补充说明:for(String word : words)
    {
    System.out.println(word);
    }等效于:for(int i = 0 ; i<words.length; i++)
    {
        System.out.println(words[i]);
    }
      

  5.   

    还有一点疑惑
    String word : words
    这个“:”代表什么意思啊?
    谢谢....啊,这个是SDK1.5新增添的Foreach功能
    说白了就是让for循环更容易罢了
    for(String word : words) 这句话如果翻译成中文,实际上的含义是
    “建立一个String的实例word,让它遍历String数组words中所有的元素”
    这个":"你可以理解为“遍历”的意思,这样以后读程序就方便理解多了