Reverse words in a string

Reversing the words in a string. For reversing the string you can refer below link.

Reverse of a string

Approach1:

public class ReverseWordString {
  public static void main(String[] args) {
    String s = "code with siri";
    System.out.println(s);
    //converting string to string array
    String[] str = s.split(" ");
    StringBuilder sb = new StringBuilder();

    for(int i=0;i<str.length;i++){
      StringBuilder temp = new StringBuilder(str[i]);
      temp.reverse();
      sb.append(temp).append(" ");
    }
    System.out.println(sb.toString().trim());
  }
}
Input: code with siri
Output: edoc htiw iris

split(): split function splits the string into a string array. String splits whenever white space is encountered.

after split() the string is converted to a string array.

str = [ "code", "with", "siri" ]

loop starts

i = 0 => str[0] = code. store code in temp then reverses the temp and space append to the outside string builder.

sb=edoc

i = 1 => str[1] = with. store code in temp then reverses the temp and space append to the outside string builder.

sb=edoc htiw

i = 2 => str[2] = with. store code in temp then reverses the temp and space append to the outside string builder.

sb=edoc htiw iris

i=3 => condition false get out of loop.

Finally, space is at the end of the string builder sb. so to revome the space we use trim().

trim(): trim method is used to remove the start and end spaces.

example: " hi A ".trim();

output: "hi A"

Approach2:

public class ReverseWordString {
  public static void main(String[] args) {
    String s = "code with siri";
    System.out.println("Input: "+s);
    //converting string to string array
    String[] str = s.split(" ");
    StringBuilder sb = new StringBuilder();
    int i=0;
    for(i=0;i<str.length-1;i++){
      sb.append(reverse(str[i])).append(" ");
    }
    if(i==str.length-1){
      sb.append(reverse(str[str.length-1]));
    }
    System.out.println("Output: "+sb);
  }

  public static String reverse(String s){
    String reverse = "";
    for(int i=s.length()-1;i>=0;i--){
      reverse+=s.charAt(i);
    }
    return reverse;
  }
}
Input: code with siri
Output: edoc htiw iris
0
Subscribe to my newsletter

Read articles from Sirisha Challagiri directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sirisha Challagiri
Sirisha Challagiri