Reverse A String Without Affecting Special Characters Using Java

String with special characters

In this tutorial you will see how to reverse a string without affecting special characters using Java programming language. You will also see in this example how to check whether a character is alphabet or digit or special character.

Your string may contain special characters such as $, #, @ etc. and you don’t want to change their positions in the string, so this example shows hot to reverse the string without changing their position. The string has to reversed and the special character must stay unchanged in the previous position. For example, “abcde” will become “edcba”, but “a$bcd” will become “d$cba”.

Prerequisites

Java

Reverse String without affecting Special Characters

Now I will write a small program that will reverse the given string without changing the position of special characters.

The below program also covers how to check whether a character is alphabet or digit or special character.

package com.roytuts.java.reverse.string.without.special.chars;

public class JavaReverseStringWithoutSpecialChar {

	public static void main(String[] args) {
		System.out.println(reverseStringWithoutSpecialChar("abcde"));
		System.out.println(reverseStringWithoutSpecialChar("a$bcd"));
	}

	public static String reverseStringWithoutSpecialChar(final String str) {
		int len = str.length() - 1;
		char[] chars = str.toCharArray();

		int i = 0;

		while (i < len) {
			char firstCh = str.charAt(i);
			char lastCh = str.charAt(len);

			if (!isAlphabet(firstCh) && !isDigit(firstCh)) {
				i++;
			} else if (!isAlphabet(lastCh) && !isDigit(lastCh)) {
				len--;
			} else {
				char temp = chars[i];
				chars[i] = chars[len];
				chars[len] = temp;
				i++;
				len--;
			}
		}

		return String.copyValueOf(chars);
	}

	private static boolean isAlphabet(char ch) {
		if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
			return true;
		}

		return false;
	}

	private static boolean isDigit(char ch) {
		if (ch >= '0' && ch <= '9') {
			return true;
		}

		return false;
	}

}

Testing the String Reverse Program

By running the above program you will get the following output:

edcba
d$cba

Source Code

Download

Leave a Reply

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