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

Updated on: 29-Mar-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements