Search code examples
javastringreverse

Reverse a sentence using StringBuilder


The below code I used string as result and just reverse sentence for example input: " the sky is blue " and I get output:"blue is sky the". How I can use SpringBuilder instead String and then how I can reverse sentence and also words? example input: " the sky is blue " and I want this output "eulb is yks eht" Please help me to modify the below code.

public String reverseWords(String s) {
    
    int i = 0;
    int j = 0;
    String result = "";
    while(s.length()>i){
        
        while(s.length()>i && s.charAt(i)==' '){
            i++;
        }
        if(i>=s.length()) break;   
        
        j = i;
        while(s.length()>j && s.charAt(j)!=' '){
            j++;
        }

        
        String word = s.substring(i,j);
        result = word+" "+result;
      
        
        i = j;
    }
    return result.trim();
}

Solution

  • You can use StringBuilder as follows:

    String str = " the  sky  is  blue ";
    str = str.replaceAll("\\s+", " ");
    StringBuilder sb = new StringBuilder(str.trim());
    System.out.println(sb.reverse().toString());
    

    Output:

    eulb si yks eht