The split() method of the String class accepts a string value representing the delimiter and splits it into an array of tokens (words), dividing the two A string between delimiters is treated as a token.
For example, if you pass a single space " " as the delimiter to this method and try to split a string. This method treats a word between two spaces as a token and returns an array of words in the current string (between spaces).
If the string does not contain the specified delimiter, this method returns an array containing the entire string as an element.
The regular expression "\W" matches all non-alphabetic characters (punctuation, spaces, underscores and special symbols) in the string.
So, to remove all non-alphabetic characters from a string:
Get the string.
Use the split() method of the String class to split the obtained string into a string array, and pass the regular expression specified above as a parameter to it .
This will split the string at each non-alphabetic character and return all tokens as a string array.
Concatenate all elements in the obtained array into a single string.
Demonstration
import java.util.Scanner; public class RemovingAlphabet { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String str = sc.nextLine(); String[] stringArray = str.split("\W+"); String result = new String(); for(int i = 0; i < stringArray.length;i++){ result = result+ stringArray[i]; } System.out.println("Result: "+result); } }
Enter your name: Krishna ^% Kasyap*@# Result: KrishnaKasyap
The above is the detailed content of Remove all non-alphabetic characters from string in Java?. For more information, please follow other related articles on the PHP Chinese website!