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

标签 java indexof

我的问题如下:

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.

我编写了以下代码:

第二个单词=句子.substring(sentence.indexOf("", 句子.indexOf(""+1)));

我不知道我在做什么,所以我希望任何关于我应该做什么的解释。请记住,我对编码非常陌生,我无法使用循环之类的东西。谢谢。

最佳答案

您可以使用 String.split("") 将句子分成“部分”,这将为您提供一个单词数组。

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

如果单词 String 数组的长度小于 2,请注意 ArrayIndexOutOfBoundsException

关于java - 如何使用 Java 中的 indexOf 找到字符串中的第二个空格字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63930841/

相关文章:

java - 是否可以在 java 应用程序 Netbeans 中使用 Iframe 网页

java - Nim 游戏,电脑不会走棋

jquery - jquery中如何获取某个字符的lastindex?

javascript - 根据元素中的单词更改图像 src

javascript - jQuery - 比较数组中的indexOF

java - 使用 java Deque 来跟踪国际象棋状态

java - 在 javadoc 中添加链接到谷歌代码上的源文件

java - 遍历器关系方向顺序neo4j java

c# - 从单词索引中获取完整的句子

Javascript 数组包含/包含子数组