共計(jì) 441 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
要將字符串按單詞逆序輸出,可以按照以下步驟進(jìn)行:
- 使用
split()
函數(shù)將字符串拆分成單詞數(shù)組。 - 創(chuàng)建一個(gè)新的字符串?dāng)?shù)組,長(zhǎng)度與單詞數(shù)組相同。
- 使用循環(huán)將單詞數(shù)組中的單詞逆序復(fù)制到新的字符串?dāng)?shù)組中。
- 使用循環(huán)輸出新的字符串?dāng)?shù)組中的單詞。
以下是一個(gè)示例代碼:
public class Main {public static void main(String[] args) {
String str = "Hello World";
String[] words = str.split("\\s+");
String[] reversedWords = new String[words.length];
for (int i = 0; i < words.length; i++) {reversedWords[i] = words[words.length - 1 - i];
}
for (String word : reversedWords) {System.out.print(word + " ");
}
}
}
輸出結(jié)果為:
World Hello
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完