Home > Java > javaTutorial > body text

Remove all non-alphabetic characters from string in Java?

WBOY
Release: 2023-08-19 15:37:10
forward
2087 people have browsed it

Remove all non-alphabetic characters from string in Java?

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.

Example

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);
   }
}
Copy after login

Output

Enter your name:
Krishna ^% Kasyap*@#
Result: KrishnaKasyap
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!