Java Program to swap first and last word of a Sentence
Answer :
import java.util.Scanner;
public class StringWordSwap {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Enter the String :");
String s=scan.nextLine();
String[] ori=s.split(" ");
//split method return type is array type. Example-if input is "give your best performance"
//after split method ori[]={"give","your","best","performance"};
String temp=ori[0];
ori[0]=ori[ori.length-1]; //"performance" will store at ori[0]
ori[ori.length-1]=temp;//"give" will store at last index
for(int i=0;i<(ori.length);i++){
System.out.print(ori[i]+" ");
}
}
}
Example:
input:give your best performance
ouput:performance your best give
No comments:
Post a Comment