【问题标题】:extracting words from a sentence using indexOf and substring and storing them in an array in java [closed]使用indexOf和子字符串从句子中提取单词并将它们存储在java中的数组中[关闭]
【发布时间】:2012-07-12 18:51:13
【问题描述】:

这是我目前对这部分程序的了解;

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

【问题讨论】:

  • 这对我来说就像是代码/作业转储。原始发帖人,请准确地告诉我们您遇到的问题,并尽快提出具体的可回答问题,否则此问题可能很快就会被关闭。
  • 这是我尝试开始工作的方法的一部分。我想将一个句子分成单个单词并将这些单词放入一个数组中
  • 它在什么方面没有达到你想要的效果?您究竟希望 SO 社区为您做什么? (我们不会做的一件事就是为你做作业。)
  • newWord 不是一个数组,所以尝试用newWord[count] 来解决它甚至不会编译...
  • 我不是要你帮我做作业,我是要你给我一些指导,说明它为什么不起作用以及我可以做些什么来使它起作用。

标签: java arrays substring indexof


【解决方案1】:

分割句子,使用String的.split()方法

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

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

【讨论】:

  • 我知道这种方法,但因为我不能用它来完成这个任务
  • 啊,好吧,我想知道...我会留下这个,这样其他人就不会再这样做了
【解决方案2】:
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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2017-10-01
    • 2015-05-07
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多