How to remove non-alphabetical characters from a string in JAVA

In this Java tutorial, we will learn how to remove non-alphabetical characters from a string in Java. You can also say that print only alphabetical characters from a string in Java. In order to explain, I have taken an input string “str” and store the output in another string “s”.

Remove non-alphabetical characters from a String in JAVA

Let’s discuss the approach first:-

  1. Take an input string as I have taken “str” here
  2. Take another string which will store the non-alphabetical characters of the input string
  3. Read the input string till its length whenever we found the alphabetical character add it to the second string taken.
  4. Now, second string stores all alphabetical characters of the first string, so print the second string ( I have taken “s” in the code below ).

Factorial of a large number using BigInteger in Java

How To check for Alphabetical Characters in a String Without using any Function

ASCII value for lower-case English alphabets range is from 97 to 122 and for upper case English alphabets it ranges from 65 to 90. So I m taking an integer ‘k’ which is storing the ASCII Value of each character in the input string. If the value of k lies in the range of 65 to 90  or  97 to 122 then that character is an alphabetical character.

Code Snippet To Check For Alphabetical Characters

 int k=str.charAt(i);
 if(k>96 && k<123 || k>64 && k<91)
    s+=str.charAt(i);

 

         Java Program To remove Alphabetical Characters from a String

class Codespeedy
{
static String count(String str)
{
    String s=" ";
for (int i = 0; i < str.length(); i++)
{
int k=str.charAt(i);

if(k>96 && k<123 || k>64 && k<91)
   s+=str.charAt(i);
   }
return new String(s);
}
public static void main(String[] args){
String str = "#(?C&[email protected]*S_[p$.e.>e<]^%d!*y";
System.out.println(count(str));
       }
}

The above code will print only alphabetical characters from a string

Output:

CodeSpeedy

Now we can see in the output that we get only alphabetical characters from the input string.



you may also read,

4 responses to “How to remove non-alphabetical characters from a string in JAVA”

  1. Alka Maurya says:

    I m new in java , but it is a simple and good explaination.

  2. Rajat says:

    Step by step nice explained with algorithm

  3. Atul Kumar says:

    Nice explained and very easy to understand

  4. Atul Kumar says:

    Very nice explaination

Leave a Reply

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