Search Bar

How to extract only characters (alphabets) from a String in Java

 

How to extract only characters (alphabets) from a String in Java - Problem Solution.


Hello, learners and coder's hope you are doing well. Today we have a coding problem to solve in JAVA.

Problem Statment: You have given a string it consists of uppercase, lowercase, special characters, numbers, and digit. You need to extract only alphabets from a given string and make it upper case.

How to extract only characters (alphabets) from a String in Java


Inputs- "A$mo102L&gaD@aGE"

Output- "AMOLGADAGE"

I am showing two ways to solve this problem statement. 

1st way: using regex and one redefine method: 

package test;

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

        String in = "A$mo102L&gaD@aGE";
        String newIn = in.replaceAll("[^a-zA-Z]", "");

        System.out.println(newIn.toUpperCase());
    }
}

As we see above we have used regex in replaceAll() method. 

  1. public String replaceAll(String regex, String replacement)  

Regex - Regular Expression - [^a-zA-Z] - only alphabets lower and upper case.

Replacement- Replacement sequence of characters. 


toUpperCase() method used to convert given text into uppercase. 


2nd way: The generic way of extraction using ASCII values.

package test;

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

        String in = "A$mo102L&gaD@aGE";
        char[] ch = in.toCharArray();
        // System.out.println(ch);

        StringBuilder newStr = new StringBuilder("");

        for (int i = 0; i < in.length(); i++) {
            // int c = ch[i];
            if ((ch[i] >= 65 && ch[i] <= 90) || (ch[i] >= 97 && ch[i] <= 122)) {
                newStr.append(ch[i]);
            }

        }
        System.out.print(newStr.toString().toUpperCase());
    }
}

ASCII acronym for American Standard Code for Information Interchange. A 7-bit character set contains 128 (0 to 127) characters. It represents the numerical value of a character. For example, 

The ASCII value of A is 65.

The ASCII value of Z is 90.

The ASCII value of a is 97.

The ASCII value of z is 122.

toCharArray():-

The java string toCharArray() method converts this string into a character array. It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.

Thank You :) 


Post a Comment

0 Comments