-1

到目前为止,这是我程序的这一部分的内容;

String text = JOptionPane.showInputDialog("enter a sentence");

String newWord = "";
char space = '_';
int count = 0;

for(int i = 0; i < text.length(); i++)
{
  int found = text.indexOf(space, i);

  int start = found + 1; // start location of substring after a space
  int end = text.indexOf(space, start); // end of word
  count = end + 1;
}
  while(count < text.length())
  {

newWord[count] = text.substring(start, end); 

  count++;

}

System.out.println(newWord[count]);
4

2 回答 2

2

要拆分句子,请使用 String 的 .split() 方法

String [] splitter = text.split(" ");

这将打破基于空格的句子。然后你可以对数组做任何你需要的事情

于 2012-07-12T22:41:44.087 回答
0
String text = JOptionPane.showInputDialog("Enter a sentence");
int count = 0;
char space = ' ';

int index = 0;
do 
{
   ++ count;
   ++ index;
   index = text.indexOf(space, index);
}
while (index != -1);

    String[] array = new String[count];
    index = 0;
    int endIndex = 0;
    for(int i = 0; i < count; i++)
    {
      endIndex = text.indexOf(space, index);

      if(endIndex == -1)
     {
       array[i] = text.substring(index);
     }else{
       array[i] = text.substring(index, endIndex);
     }

     index = endIndex + 1;
    }
    for(String s : array)
    {
      System.out.println(s);
    }
于 2012-07-13T14:17:34.220 回答