Programming Examples

Java Program to Swap first and last character of each words in a Sentence


Write a Java Program to Swap first and last character of each words in a Sentence .

Example:

Input: infomax computer academy

Output: xnfomai romputec ycadema

Solution

import java.util.*;
class SwapFirstLastCharacters 
{ 
    public static void main(String[] args) 
    { 
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter any String");
        String str = sc.nextLine(); 
        char[] ch = str.toCharArray(); 
        for (int i = 0; i < ch.length; i++) 
        { 
            int k = i; 
            while (i < ch.length && ch[i] != ' ')  
            {
                i++; 
            }  
            char temp = ch[k]; 
            ch[k] = ch[i - 1]; 
            ch[i - 1] = temp;
        }
        System.out.println(String.valueOf(ch)); 
    } 
} 
Output


CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz