2

我正在制作一个程序,让用户输入一个句子,然后,应用程序会将字符串分解为子字符串,其中空格是原始字符串的分解。

import java.util.StringTokenizer;


    public class whitespace {

    public static void main(String[] args) {

    String text = "supervisors signature tom hanks";
    int tokenCount; //number of words
    int idx=0; // index
    String words[]=new String [500]; // space for words


     StringTokenizer st=new StringTokenizer(text); // split text into segements
     tokenCount=st.countTokens(); 
     while (st.hasMoreTokens()) // is there stuff to get?
     {
         words[idx]=st.nextToken();
         idx++;
     }
}

到目前为止,我有这段代码,虽然它可以作为常规 Java 程序正常工作,但 while 循环似乎导致应用程序进入无限循环。有任何想法吗?

4

5 回答 5

5

我认为您可以为此使用String.split方法:

String text = "supervisors signature tom hanks";
String[] tokens = text.split("\\s+");
for (String str : tokens)
{
    //Do what you need with your tokens here.
}

只要遇到一个或多个空格字符,正则表达式就会将文本拆分为句子。

根据页面,StringTokenizer 已被 String.split 替换。

于 2012-03-06T12:27:41.827 回答
4

用这个:

words = text.split(" ");
于 2012-03-06T12:26:34.587 回答
1
String[] words = text.split(" ");
于 2012-03-06T12:26:59.407 回答
1

使用阿帕奇StrTokenizer

StrTokenizer strTok = new StrTokenizer(text);
String[] strList = strTok.getTokenArray();

http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/text/StrTokenizer.html

于 2012-03-06T12:31:20.547 回答
0
StringTokenizer sta=new StringTokenizer(text); // split text into segements
     String[] words= new String[100];int idx=0;
     while (sta.hasMoreTokens()) // is there stuff to get?
     {
         words[idx]=sta.nextToken();
         System.out.println(words[idx]);
         idx++;
     }

这就是我复制您的代码并通过少量更改来执行的内容,并且效果很好。

于 2012-03-06T12:36:38.410 回答