Reverse the sentence without changing punctuation

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

  1. We are going to use ArrayList to store the position of punctuation.
  2. First, get the string and store the character in char array if it is letter or digit in reverse order.
  3. Then, store the index of punctuations in ArrayList.
  4. 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++;
			}
		}
	}
}

Follow For Instant Updates

Join WhatsApp Group: link
Join our Telegram Channel: link
Like our Facebook Page:  link
Subscribe to our Youtube channel: link

Sree Hari Sanjeev

The founder of Wisdom Overflow. Software Developer at Zoho Corporation.
0 0 votes
Article Rating
Subscribe
Notify of
guest
5.4K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
5.4K
0
Would love your thoughts, please comment.x
()
x