Search code examples
javaarraysstringcharacter

Reverse a string word by word except the last letter of each word


I'd like to reverse a string word by word except the last letter of each word.

For example: "Hello how are you" -> lleHo ohw rae oyu

but I am getting output as: olleH woh era uoy

I'm not able to fix the last letter of each word.

This is my Java code for the above output:

public class Main

    {
    public static void main(String[] args) {
     String s = "Hello how are you  ";
      char [] ch = s.toCharArray();
      System.out.println(ch.length);
      int pos=0;
        for(int i=0;i<ch.length;i++)
        {
        
            if(ch[i]==' ')
            {
                   
                for(int j=i;j>=pos;j--)
                {
                    System.out.print(ch[j]);
                }
                pos=i+1;
                }
            }
    
    }
} 

Solution

  • Below is the solution to solve the problem:

    public class Main { 
        
        public static void main(String[] args) { 
            //call the reverseSentence Method
            reverseSentence("Hello how are you");
        } 
        
        public static void reverseSentence(String sentence) {
            
    
            //Replacing multiple space with a single space
            sentence = sentence.replaceAll("[ ]{2,}", " ");
    
            //Split the array and store in an array
            String [] arr = sentence.split(" ");
            
            StringBuilder finalString = new StringBuilder();
            
            //Iterate through the array using forEach loop
            for(String str : arr) {
                
                //Creating substring of the word, leaving the last letter
                String s = str.substring(0, str.length() - 1);
                
                //Creating StringBuilder object and reversing the String
                StringBuilder sb = new StringBuilder(s);
                //Reversing the string and adding the last letter of the work again.
                s = sb.reverse().toString() + str.charAt(str.length() - 1);
                
                //Merging it with the final result
                finalString.append(s).append(" ");
            }
            
            //Printing the final result
            System.out.println(finalString.toString().trim());
        }
    } 
    

    What I have done is, firstly split all the words on spaces and store it inside an array. Now iterate through the array and get the substring from each word leaving the last letter of each word. And then I am using StringBuilder to reverse the String. Once that is done I am adding the last letter of the word to the reversed string and merging it with the finalString which is created.