- 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 Pair of Characters
In this article, we will understand how to swap pair of characters in Java. We will convert the given string to character array. This will allow us to swap pair of characters.
Below is a demonstration of the same −
Suppose our input is −
Input string: Java program
The desired output would be −
The string after swapping is: Javg proaram
Algorithm
Step 1 - START Step 2 - Declare a string value namely input_string, a char array namely character, and a string object namely result. Step 3 - Define the values. Step 4 - Convert the string to character array. Step 5 - Swap the character using a temp variable. Step 6. Convert the character back to string. Step 7 - Display the string Step 8- Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
public class SwapCharacter { public static void main(String args[]) { String input_string = "Java program"; System.out.println("The string is defined as: " +input_string); int i = 3, j = input_string.length() - 4; char character[] = input_string.toCharArray(); char temp = character[i]; character[i] = character[j]; character[j] = temp; String result = new String(character); System.out.println("\nThe string after swapping is: " +result); } }
Output
The string is defined as: Java program The string after swapping is: Javg proaram
Example 2
Here, we encapsulate the operations into functions exhibiting object-oriented programming.
public class SwapCharacter { static char[] swap(String input_string, int i, int j) { char character[] = input_string.toCharArray(); char temp = character[i]; character[i] = character[j]; character[j] = temp; return character; } public static void main(String args[]) { String input_string = "Java program"; System.out.println("The string is defined as: " +input_string); System.out.println("\nThe string after swapping is: "); System.out.println(swap(input_string, 3, input_string.length() - 4)); } }
Output
The string is defined as: Java program The string after swapping is: Javg proaram
Advertisements