Remove All Non-Alphabetical Characters of a String in Java



When you are working with strings in Java, you may want to keep only the alphabetic characters (A-Z, a-z) and remove everything else, like numbers, punctuation, and symbols. Java gives you multiple ways to do this for different cases or scenarios.

Removing non-alphabetical characters from a string

There are different methods, and they are -

  • Using split() method

  • Using replaceAll() method

  • Using character.isLetter() method with StringBuilder

  • Using Java Streams

Now, we will discuss each method one by one -

Using split() method

The split() method of the String class accepts a String value representing the delimiter and splits into an array of tokens (words), treating the string between the occurrences of two delimiters as one token.

For example, if you pass a single space " " as a delimiter to this method and try to split a String. This method considers the word between two spaces as one token and returns an array of words (between spaces) in the current String.

If the String does not contain the specified delimiter, this method returns an array containing the whole string as an element. The regular expression "\W+" matches all the non-alphabetical characters (punctuation marks, spaces, underscores, and special symbols) in a string.

import java.util.Scanner;
public class RemovingAlphabet {
   public static void main(String args[]) {
      String str = "Krishna ^% Kasyap*@#";
      String[] stringArray = str.split("//W+");
      String result = new String();
      for(int i = 0; i < stringArray.length;i++){
         result = result+ stringArray[i];
      }
      System.out.println("Original String: "+ str);
      System.out.println("Result: "+result);
   }
}

Let us compile and run the above program, this will give the following result -

Krishna ^% Kasyap*@#
Result: KrishnaKasyap

By using this method, we can remove non-alphabetic characters of a string, but it's still not an ideal or optimal solution.

Limitations of split() method

As it is not an optimal solution and has some limitations and they are as follows -

  • It creates an array of substrings which uses more memory.

  • It can give false outputs with consecutive non-alphabetical characters.

  • It is not as intuitive or readable as other method solutions.

  • This method is used for tokenizing strings, not character filtering.

Using replaceAll() method

The replaceAll() method is a built-in method of the String class in Java. It is used to replace all parts of a string that match a given regular expression (regex) with a new string.

import java.util.Scanner;

public class RemoveNonAlphabetChars {
   public static void main(String[] args) {

      // Asking user to enter a string
      String input = "Manisha@#$%1323 Chand";

      // Removing all non-alphabetic characters using replaceAll()
      String result = input.replaceAll("[^a-zA-Z]", "");

      // Displaying the cleaned string
	  System.out.println("Original String: "+ input);
      System.out.println("String after removing non-alphabetic characters: " + result);
   }
}

Let us compile and run the above program, which will give the following result -

Enter a string with special characters, numbers, etc: Manisha@#$%1323 Chand
String after removing non-alphabetic characters: ManishaChand

Using Character.isLetter() method with StringBuilder

This method removes non-alphabetic characters using Character.isLetter() and StringBuilder checks each character in the input string. Character.isLetter(char) identifies letters (both uppercase and lowercase) and skips all other characters like digits, spaces, and symbols.

Instead of using string concatenation (which is less efficient), it uses a StringBuilder to collect and make the result string by appending only the alphabetic characters. This makes it faster and more memory-efficient, especially for long strings.

import java.util.Scanner;

public class RemoveNonAlphabetic {
   public static void main(String[] args) {

      String input = "Manisha@#$$342345c h an d";

      // Removing non-alphabetic characters
      StringBuilder result = new StringBuilder();
      for (int i = 0; i < input.length(); i++) {
         if (Character.isLetter(input.charAt(i))) {
            result.append(input.charAt(i));
         }
      }

      // Printing the cleaned string
      System.out.println("Original String: "+ input);
      System.out.println("String after removing non-alphabetic characters: " + result.toString());
   }
}

Let us compile and run the above program, this will give the following result -

Enter a string: Manisha@#$$342345c h an d
String after removing non-alphabetic characters: Manishachand

Using Java Streams

In Java, a Stream is an abstraction that allows you to process sequences of elements (e.g., collections like lists, sets, arrays, or even I/O resources) in a functional way. Java Streams provide a more concise and flexible approach to handling data transformations, computations, and aggregations, compared to the traditional iterative methods.

We will use the chars() method of a string, which gives us a stream of int values representing each character (ASCII values). Then we filter out only the characters that are alphabetic using Character.isLetter(), convert them back to characters, and join them into a final string.

import java.util.Scanner;
import java.util.stream.Collectors;

public class StreamRemoveNonAlphabetic {
   public static void main(String[] args) {

      String input = "Manisha4c@#$h15454and";

      // Removing non-alphabetic characters using Java Streams
      String result = input.chars()
         .filter(Character::isLetter)
         .mapToObj(c -> String.valueOf((char) c))
         .collect(Collectors.joining());

      // Displaying the result
	  System.out.println("Original String: "+ input);
      System.out.println("String after removing non-alphabetic characters: " + result);
   }
}

Let us compile and run the above program, this will give the following result -

Enter a string: Manisha4c@#$h15454and
String after removing non-alphabetic characters: Manishachand
Updated on: 2025-04-22T11:22:42+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements