Junior — Middle
What methods can be used to reverse the order of words in a string?
sobes.tech AI
Answer from AI
To reverse the order of words in a string, you can:
- Split the string into words using
split. - Reverse the array of words.
- Join the words back into a string.
Example in Java:
String sentence = "Example string for reversal";
String[] words = sentence.split(" ");
// Reverse the array of words
for (int i = 0; i < words.length / 2; i++) {
String temp = words[i];
words[i] = words[words.length - 1 - i];
words[words.length - 1 - i] = temp;
}
String reversed = String.join(" ", words);
System.out.println(reversed); // "reversal for string Example"
You can also use collections and methods from Collections:
List<String> wordList = Arrays.asList(words);
Collections.reverse(wordList);
String reversed = String.join(" ", wordList);
Both methods are effective and widely used.