Sobes.tech
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:

  1. Split the string into words using split.
  2. Reverse the array of words.
  3. 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.

What methods can be used to reverse the order of… - sobes.tech