Reverse each word in a given sentence in java.

 package program;

import java.util.Scanner;
public class code{
public static void reverse(StringBuilder sb, int i, int j){
    while(i<j){
    char t = sb.charAt(i);
    sb.setCharAt(i,sb.charAt(j));
    sb.setCharAt(j,t);
    i++;
    j--;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter sentence=");
StringBuilder sb = new StringBuilder(sc.nextLine());
int n = sb.length();
int i=0,j=0;
while(j<n){
    if(sb.charAt(j)!=' ')
        j++;
    else{
         reverse(sb, i, j-1);
         i=j+1;
         j=i;
    }
}
reverse(sb, i,j-1);
System.out.println("reverse sentence is=");
System.out.println(sb);
}  
}

Comments

Popular posts from this blog

Introduction of java Programming language.

Stack data structure.