Java program to swap first and last characters of words in a sentence

Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example?

Examples:

Input : geeks for geeks
Output :seekg rof seekg

Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is.

  • First we will create an Char array of given String by using toCharArray() method.
  • Now we iterate the char array by using for loop.
  • In for loop, we declare a variable whose value is dependent on i.
  • Whenever we found an alphabet we increase the value of i and whenever we reach at space, we are going to perform swapping between first and last character of the word which is previous of space.
filter_none

edit
close

play_arrow

link
brightness_4
code

class SwapFirstLastCharacters {
    static String count(String str)
    {
        // Create an equivalent char array
        // of given string
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
  
            // k stores index of first character
            // and i is going to store index of last 
            // character. 
            int k = i;
            while (i < ch.length && ch[i] != ' '
                i++;
              
            // Swapping
            char temp = ch[k];
            ch[k] = ch[i - 1];
            ch[i - 1] = temp;
  
            // We assume that there is only one space
            // between two words.
        }
        return new String(ch);
    }
    public static void main(String[] args)
    {
        String str = "geeks for geeks";
        System.out.println(count(str));
    }
}

chevron_right


Output:

seekg rof seekg


My Personal Notes arrow_drop_up

Hello everyone, I am Bishal KUMAR Dubey and most importantly an idea creator. I just love Programming languages and love to know new concepts everyday,every minute,every second. Here to help Other GEEKS!!!

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.