Java program to remove characters in a string except alphabets

Remove character in a String except alphabet

In this java program, we’re going to make a program to remove character in a string except for the alphabet. Take String input from the user and store it in a variable called “s”(in this case). After that use replaceAll() method which was present in string class the work of replaceAll() method is to replace some old thing with some new thing so here we’re using a regular expression to replace character in a string with blank spaces.

Java program to remove character from string except alphabet

Algorithm

  • Take String input from user and store it in a variable called “s”.
  • After that use replaceAll() method.
  • Write regex to replace character with whitespaces like this s.replaceAll(“[^a-zA-Z]”,””);.
  • After that simply print the String after removing character except alphabet.

Code in Java

import java.util.Scanner;

class RemoveCharactersInAtringExceptAlphabets {

public static void main(String[] args) {
     Scanner sc =new Scanner(System.in);
     System.out.print("Enter String : ");
     String s = sc.nextLine();
     s=s.replaceAll("[^a-zA-Z]","");
     System.out.println(s);
   }
}
This code is contributed by Shubham Nigam (Prepinsta Placement Cell Student)

Output

Enter String : hel1456lo56wor%^ld
helloworld

2 comments on “Java program to remove characters in a string except alphabets”


  • Vaibhav

    package stringprogram;

    import java.util.Scanner;

    public class RemoveCharactersInAtringExceptAlphabetsWithoutUsingApi {

    public static void main(String[] args)
    {

    Scanner sc =new Scanner(System.in);
    System.out.print(“Enter String : “);
    String Str1 = sc.nextLine();
    String Str2=””;
    for(int i=0;i=65 && (int)Str1.charAt(i)=97 && (int)Str1.charAt(i) “+Str2);

    }

    }