我的问题如下:
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/