使用indexOf和substring从句子中提取单词并将其存储在java中的数组中

使用indexOf和substring从句子中提取单词并将其存储在java中的数组中,java,arrays,substring,indexof,Java,Arrays,Substring,Indexof,这是我到目前为止为我的计划的这一部分所做的 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; /

这是我到目前为止为我的计划的这一部分所做的

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]);
String text=JOptionPane.showInputDialog(“输入句子”);
字符串newWord=“”;
字符空间='';
整数计数=0;
对于(int i=0;i
要拆分句子,请使用String的.split()方法

这将打破基于空格的句子。然后可以对数组执行任何需要的操作

String text=JOptionPane.showInputDialog(“输入句子”);
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);
    }
整数计数=0; 字符空间=“”; int指数=0; 做 { ++计数; ++指数; index=text.indexOf(空格,索引); } 而(索引!=-1); 字符串[]数组=新字符串[计数]; 指数=0; int-endIndex=0; for(int i=0;i
在我看来,这就像是一个代码/作业转储。原创海报,请准确地告诉我们你被困在哪里,并尽快提出一个具体的可回答问题,否则这个问题很快就会结束。这是我正在尝试的工作方法的一部分。我想把一个句子分成几个单独的单词,然后把这些单词放到一个数组中。什么样的句子不符合你的要求?你到底希望SO社区为你做什么?(我们不会做的一件事是为您做家庭作业。)
newWord
不是数组,所以尝试用
newWord[count]来解决它
甚至不会编译…我不是要求你帮我做作业,我是要求你给我一些指导,说明为什么它不起作用,以及我能做些什么来让它起作用。我知道这种方法,但因为我不能在这个任务中使用它啊,好吧,我想知道…我会把它留下,这样其他人就不会再做了
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);
    }