Swap even and odd characters in a string Java

  • by

Here in this page I have written a Java class which will swap even and odd characters in a string. So, let’s get started. Before we begin, take a look the following code. I have not included any library here. I have written it out of basic core Java.

Code

package com.cloudiknow;

public class EvenOddSwap {
	public static void main(String[] args) {
		// here we are going to swap even with odd character
		String str = "CloudiKnow";
		String output = "";
		for (int i = 0; i < str.length(); i++) {
			// swap only if the next char is within the string
			if (i + 1 < str.length()) {
				output = output + str.charAt(i + 1);
				output = output + str.charAt(i);
			}
			i = i + 1;
		}
		System.out.println("Given   String: " + str);
		System.out.println("Swapped String: " + output);
	}
}

Output

Given   String: CloudiKnow
Swapped String: lCuoidnKwo

Code Explanation

I have taken a string as ‘str’. Then to generate output, I have given an another empty string. In the ‘for’ loop I will be iterating through 0 to the length of string ‘str’. I have an ‘if’ condition to check if the first character that we are taking has an adjacent character or not. If we do not have an adjacent character then we will skip it.

If we have an adjacent character then we will place that character at the beginning of the output and then the current character at the next position of output.

This will be looped till we have any characters left in the string. Once the loop is completed then the output will be printed along with the given string to compare. You can have a look at the output which I have given in the above immediately after the code.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

We are sorry that this post was not useful for you!

Let us improve this post!

Tags:

Leave a Reply

Welcome to CloudiKnow.com blog, a platform to share knowledge and solution experience related to public cloud is base design of this site.

You can start the cloud journey right from here!
Please bookmark this page by pressing simply CTRL+D.