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


Following is the Java program to swap first and last characters of word in a sentence −

Example

 Live Demo

public class Demo {
   static String swap_chars(String my_str) {
      char[] my_ch = my_str.toCharArray();
      for (int i = 0; i < my_ch.length; i++) {
         int k = i;
         while (i < my_ch.length && my_ch[i] != ' ')
            i++;
            char temp = my_ch[k];
            my_ch[k] = my_ch[i - 1];
            my_ch[i - 1] = temp;
      }
      return new String(my_ch);
   }
   public static void main(String[] args) {
      String my_str = "Thas is a sample";
      System.out.println("The string after swapping the last characters of every word is : ");
      System.out.println(swap_chars(my_str));
   }
}

Output

The string after swapping the last characters of every word is :
shaT si a eampls

Explanation

A class named Demo contains a function named ‘swap_chars’ which returns a string as output. In this function, the string is converted to a character array. The character array is iterated over, and if the next element in the word is not a space, the first and the last elements are swapped, and this string is returned as output of the function. The same is repeated for all words in a sentence. In the main function, the string is defined, and the function is called by passing this string as a parameter to it.

Updated on: 14-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements