使用Java中的indexOf如何找到字符串中第二个空格字符?

huangapple go评论66阅读模式
英文:

How can I find a second space character in a string using indexOf in Java?

问题

我的问题如下:

假设句子是一个已赋值的String类型变量。进一步假设这个值是一个由以单个空格字符分隔的单词组成的String,末尾带有句号。例如:"This is a possible value of sentence."

再假设还有另一个声明的变量secondWord,也是String类型。编写所需的语句,以便将句子的值中的第二个单词赋值给secondWord。因此,如果句子的值是"Broccoli is delicious.",您的代码将把"is"赋值给secondWord。

我已经写了以下代码:

secondWord = sentence.substring(sentence.indexOf(" ", sentence.indexOf(" ") + 1));

我不知道自己在做什么,所以我会欣赏对我应该做什么的任何解释。请记住,我对编程非常新手,不能使用诸如循环之类的东西。谢谢。

英文:

My problem is as follows:
>Assume that sentence is a variable of type String that has been assigned a value. Assume furthermore that this value is a String consisting of words separated by single space characters with a period at the end. For example: "This is a possible value of sentence."

>Assume that there is another variable declared, secondWord, also of type String. Write the statements needed so that the second word of the value of sentence is assigned to secondWord. So, if the value of sentence were "Broccoli is delicious." your code would assign the value "is" to secondWord.

I have written the following code:

secondWord = sentence.substring(sentence.indexOf(" ", sentence.indexOf(" "+1)));

I have no idea what I'm doing so I would appreciate any explanation of what I should do. Keep in mind I'm very new to coding and I can't use things like loop. Thank you.

答案1

得分: 3

你可以使用 String.split(" ") 将句子分割成“部分”,这将给你一个单词数组。

String[] words = sentence.split(" ");
String secondWord = words[1];   //从 0 开始

如果单词的字符串数组长度小于 2请注意 `ArrayIndexOutOfBoundsException`。
英文:

You could split the sentence into "parts" using String.split(" ") which will give you an array of the words.

String[] words = sentence.split(" ");
String secondWord = words[1];   //0 based

Watch out for ArrayIndexOutOfBoundsException if the words String array has a length less than 2

答案2

得分: 0

如果必须使用 indexOf,就像这样:

sentence.substring(sentence.indexOf(" ") + 1, sentence.indexOf(" ", sentence.indexOf(" ") + 1));

但更好的方法是像 @tomgeraghty3 一样。

英文:

If you must use indexOf,just like this:

sentence.substring(sentence.indexOf(" ") + 1, sentence.indexOf(" ", sentence.indexOf(" ") + 1));

But the better way is what like @tomgeraghty3

huangapple
  • 本文由 发表于 2020年9月17日 11:30:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63930841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定