chevron_left
275 points
10 4 4

In java, string is a sequence of characters within Unicode representations. Hence Unicode definitions are includes both alphabetic and non-alphabetic characters. So if we have purpose of data validation, then sometime we have to remove non-alphabetic characters from a set of given strings. Let's find out the technique to remove non-alphabetic characters from string.

Removing non-alphabetic characters from string

  • Hence alphabetic characters can be determined by using regular expression (Regex). So that we can use regex to filter the set of characters such as alphabetic or non-alphabetic.
  • If regex match such a condition that character is not a alphabetic, i.e: "[^a-zA-Z]", then simply replace it by a empty character, "”.
  • Then format the string and replace the main string reference by the newly formatted string.

Code Example:

import java.util.Scanner;

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Input your strings:\t"); 
        Scanner sc = new Scanner(System.in);
        String[] inputs = new String[5];
        for(int i = 0; i < 5; i++){
            inputs[i] = sc.nextLine();
        }
        inputs = inputValidator(inputs);
        
        for(int i = 0; i < 5; i++){
            System.out.println(inputs[i]); 
        }
    }
    
    static String[] inputValidator(String[] line) {
        for(int i = 0; i < line.length; i++) {
           line[i] = line[i].replaceAll("[^a-zA-Z]", "");
           line[i] = line[i].toLowerCase();
        }
        return line;
    }
}

Example Input:

No money = No work
Everybody works for $$$ or £££, not for humankind!
"Rain! Rain! I saw it."
about 1% of Covid19 affected people are going to severe.
You & me, #Meet_Up!

Example Output:

nomoneynowork
everybodyworksforornotforhumankind
rainrainisawit
aboutofcovidaffectedpeoplearegoingtosevere
youmemeetup

1 Comment

Nice explanation about non alphabetic character from string. Continue to post:)

Thanks you sir:

More Posts

First non-repeated characters in a string java MallikaShaik672 - Oct 23, 2020
Remove character from the particular position in C++ Lalit Kumar - Sep 10, 2020
Write a Java program to find first non repeating character in a string Being human - May 28
Java program to find duplicate characters in a string Jeevani - Jun 10
Write a java program to count the letters, spaces, numbers and other characters of an input string. Jeevani - Jun 7
How to remove the first character of a string in java Hasnain_khan - Oct 12, 2020
HOW TO REMOVE SUBSTRING FROM STRING IN PYTHON jaseera - Oct 23, 2020
HOW TO REMOVE A SUBSTRING FROM STRING IN PYTHON - Oct 23, 2020
Remove first character from string c++ zeeshan - Jul 19, 2020
How to remove the last character from the string in C++? Lalit Kumar - Jun 19, 2020