Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Java program to swap first and last characters of words in a sentence
Problem Statement
Given a sentence, create a program in Java that swaps the first and last characters of each word efficiently as given below ?
Input
That is a sample
Output
The string after swapping the last characters of every word is : thaT si a eampls
Steps to swap first and last characters of words in a sentence
Below are the steps to swap first and last characters of words in a sentence ?
- Convert string to character array.
- Iterate through the character array using while loop to identify the beginning and end of each word.
- For each word, swap the first and last characters.
- Convert the modified character array back into a string and return it.
Java program to swap first and last characters of words in a sentence
public class Demo {
static String swap_chars(String my_str) {
char[] my_ch = my_str.toCharArray();
for (int i = 0; i < my_ch.length; i++) {
int k = i;
while (i < my_ch.length && my_ch[i] != ' ')
i++;
char temp = my_ch[k];
my_ch[k] = my_ch[i - 1];
my_ch[i - 1] = temp;
}
return new String(my_ch);
}
public static void main(String[] args) {
String my_str = "That is a sample";
System.out.println("The string after swapping the last characters of every word is : ");
System.out.println(swap_chars(my_str));
}
}
Output
The string after swapping the last characters of every word is : thaT si a eampls
Code explanation
The Demo class contains a method called swap_chars() that returns a string. In this method, the input string my_str is converted to a character array my_ch using the toCharArray() method. A for loop iterates over the character array my_ch using its length, my_ch.length. Within the loop, an integer k stores the current index. A while loop then iterates as long as i is less than my_ch.length and my_ch[i] is not a space. For each word, if the next character is not a space, it swaps the first and last characters.
After processing all words, the modified character array is converted back to a string and returned. In the main method, the string my_str is defined, and the swap_chars() method is called with this string as a parameter. The result is then printed to the console.
