- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to swap first and last characters of words in a sentence
Following is the Java program to swap first and last characters of word in a sentence −
Example
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 = "Thas 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 : shaT si a eampls
Explanation
A class named Demo contains a function named ‘swap_chars’ which returns a string as output. In this function, the string is converted to a character array. The character array is iterated over, and if the next element in the word is not a space, the first and the last elements are swapped, and this string is returned as output of the function. The same is repeated for all words in a sentence. In the main function, the string is defined, and the function is called by passing this string as a parameter to it.
- Related Articles
- Python Program to Swap the First and Last Value of a List
- Java Program to Swap Pair of Characters
- Java program to sort words of sentence in ascending order
- Java Program to convert first character uppercase in a sentence
- Python program to count words in a sentence
- Java program to remove all duplicates words from a given sentence
- Python program to sort Palindrome Words in a Sentence
- Java program to count the characters in each word in a given sentence
- Count words in a sentence in Python program
- C++ program to check if first and the last characters of string are equal
- Java Program to search for last index of a group of characters
- Java Program to Interchange Elements of First and Last in a Matrix Across Rows
- Java Program to Interchange Elements of First and Last in a Matrix Across Columns
- Program to swap string characters pairwise in Python
- PHP program to find the first word of a sentence

Advertisements