C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programs » Java basic programs

Java program to swap first and last character of each word in a string

Here, we are implementing a java program that will read a string and we have to swap first and last character of each word in given string.
Submitted by Chandra Shekhar, on January 08, 2018

Given a string and we have to swap (exchange) first and last character of each word using java program.

Example:

    Input: "We are programmers"
    Output: "eW era srogrammerp"

Program to swap (exchange) first and last character of each word in string in java

import java.io.*;

class ExchangeFirstAndLast
{
	// create object.
	static BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
	String sentence, reverse;
	int size;
 
	// default constructor
	ExchangeFirstAndLast() 
	{
		sentence="";
		reverse="";
		size=0;
	}
 
	// create function to read sentence.
	void ReadSentence()throws IOException
	{
		// enter the sentence here.
		System.out.print("Enter the sentence : ");
		
		sentence=br.readLine();
		size=sentence.length();
		
		// check the ending of sentence with full stop.
		if(sentence.charAt(size-1)!='.') 
		{ 
			// if it is not finished with '.' then add it in last.
			sentence=sentence+".";
			size=size+1;
		}
	}
 
	void exfirstlast()
	{
		// create string variable.
		String s1=""; 
		char ch;
		for(int i=0;i<size;i++)
		{
			ch=sentence.charAt(i);
			if(ch!=' ' && ch!='.')
			{
				s1=s1+ch;
			}
			else
			{
				// find length of the word.
				int l=s1.length(); 
				
				for(int j=0;j<l;j++)
				{
					// exchange the first alphabet with the last
					if(j==0) 
						ch=s1.charAt(l-1);
					// exchange the last alphabet with the first
					else if(j==(l-1)) 
						ch=s1.charAt(0);
					else
						ch=s1.charAt(j);
					reverse=reverse+ch;
				}
				reverse=reverse+" ";
				s1=""; 
			}
		}
	}
 
	// create display function.
	void display()
	{
		System.out.println("The Original Sentence is : "+sentence);
		System.out.println("The Changed Sentence is : "+reverse);
	}
 
	public static void main(String args[])throws IOException
	{
		ExchangeFirstAndLast ob=new ExchangeFirstAndLast();
		ob.ReadSentence();
		ob.exfirstlast();
		ob.display();
	}
}

Output

First run:
Enter the sentence : We are Inclusehelp providing knoeledge to everyone.
The Original Sentence is : We are Inclusehelp providing knoeledge to everyone.
The Changed Sentence is : eW era pnclusehelI grovidinp enoeledgk ot everyone 

Second run:
Enter the sentence : We are programmers
The Original Sentence is : We are programmers.
The Changed Sentence is : eW era srogrammerp 


Advertisements




Liked this article? Do share with your friends :)


COMMENTS