Reverse the sentence without changing punctuation
Question
Reverse the sentence without changing punctuation. The position of the punctuations must be maintained.
Logic
- First, identify the characters and store them separately in reverse order.
- Identify the index position of punctuations (‘: ‘, ‘@’ , ‘ ‘, ‘&’ ,etc)
- Print the characters if the index position is not the position of punctuation.
- If the position is same then print the punctuation.
Algorithm
- We are going to use ArrayList to store the position of punctuation.
- First, get the string and store the character in char array if it is letter or digit in reverse order.
- Then, store the index of punctuations in ArrayList.
- Print the character if the index is not in the ArrayList.
Program
import java.util.ArrayList; class Reverse { public static void main(String as[]) { String str ="house22 no : 123@ cbe"; int count=0,i,len=str.length(),j; ArrayList<Integer> index = new ArrayList<>(); char c[]=new char[len]; for(i=len-1,j=0;i>=0;i--) // check in reverse direction { char t = str.charAt(i); if(Character.isLetter(t) ||Character.isDigit(t)) //built in function to check whether letter or digit { c[j]=t; j++; // increment only if the element stored } } for(i=0;i<len;i++) { char g = str.charAt(i); if( !Character.isLetter(g)&&!Character.isDigit(g)) // check whether punctuation index.add(count); count++; } for(i=0,j=0;i<len;i++) { if(index.contains(i)) // if the index present in list, print System.out.print(str.charAt(i)); else { System.out.print(c[j]); //print the character and increment j j++; } } } }