Introduction

In this tutorial we will see how to reverse a string without affecting special characters using Java programming language. We 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 we 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 Program

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

edcba
d$cba

Download Source Code

Thanks for reading.

Tags:

Leave a Reply

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