Write a java program to Swap Characters.

Write a program to input a String and swap every 2 characters in the string. If size is an odd number then keep the last letter as it is. Print the final swapped string.

The return type (String) should return the character swapped string.

Input and Output Format:

Input consists of a string.

The output consists of a string.

Refer sample output for formatting specifications.

Sample Input 1:

TRAINER

Sample Output 1:

RTIAENR

Sample Input 2:

TOM ANDJERRY

Sample output 2:

OT MNAJDREYR

Swap Characters in Java.

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s1 = sc.nextLine();
    getvalues(s1);
  }

  public static void getvalues(String s1) {
    StringBuffer sb = new StringBuffer();
    int l = s1.length();
    if (l % 2 == 0) {
      for (int i = 0; i < s1.length() - 1; i = i + 2) {
        char a = s1.charAt(i);
        char b = s1.charAt(i + 1);
        sb.append(b).append(a);
      }
      System.out.println(sb);
    } else {
      for (int i = 0; i < s1.length() - 1; i = i + 2) {
        char a = s1.charAt(i);
        char b = s1.charAt(i + 1);
        sb.append(b).append(a);
      }
      sb.append(s1.charAt(l - 1));
      System.out.println(sb);
    }
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *

one × 1 =