3 回答

TA貢獻1796條經(jīng)驗 獲得超4個贊
如果你確定正好有 2 個單詞,那么你可以這樣做:
String myString = "Hello World";
int indexOfFirstSpace = myString.indexOf(" ");
String firstWord = myString.substring(0, indexOfFirstSpace);
String secondWord = myString.substring(indexOfFirstSpace + 1);
第二個單詞是從索引到空格索引之后的子字符串,一直到字符串的末尾。
如果不確定有多少個單詞,不妨使用split拆分字符串:
String[] words = myString.split(" ");
if (words.length >= 2) {
String firstWord = words[0];
String seconfWord = words[1];
}

TA貢獻1824條經(jīng)驗 獲得超8個贊
String myString = "Hello world";
index(" ") will always give you the index of first occurrence of " ". So in
String firstWord = myString.substring(0, myString.indexOf(" "));
you start with character at 0th index and end index will be first occurrence " " which is not included.
Hello
Now in your second
String secondWord= myString.substring(1, myString.last indexOf(" "));
you are going to start with second character.
ello
**If you want to get words based in space as a separator the right way is to use split**
**Example**
String[] words = myString.split("\\s+");
firstWord = words[0];
secondWord = words[1];

TA貢獻1826條經(jīng)驗 獲得超6個贊
secondWord= myString.substring(1, myString.indexOf(" "));
為什么您的代碼不起作用: 對于上面的代碼行,您從字符串的“1”索引開始。索引 1 從“e”開始,因為您從 0 開始計數(shù)。因此,當您從“e”開始并停在下一個空格“”時,那將不起作用,因為它只會將單詞放在“e”之間“ 和 ” ”。結果是 ello (注意。它不包括空格)
要修復此運行: secondWord= myString.substring(myString.indexOf(" "), 11);
或secondWord= myString.substring(6, 11);
請注意結束索引,例如,在我們的示例中來自 的 11myString.substring(6, 11)
是當前計算機索引的一個加號 (+)。在本例中,字母“d”的索引為 10,但您始終將結尾索引加一。
添加回答
舉報