Home >Java >javaTutorial >Remove all non-alphabetic characters from string in Java?

Remove all non-alphabetic characters from string in Java?

WBOY
WBOYforward
2023-08-19 15:37:102154browse

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);
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete