Java Program to Remove all Numbers from a string.

This tutorial will guide you to learn how to remove numbers from a string in java.
Often times we may want to separate the numbers from a user-defined string, this is one of the ways in Java to solve such complexity.
A string is a collection of an alphabetical arrangement of all the 26 available characters in the English Language and also can contain numeric values and special characters. Whereas the decimal number system is a collection of all the digits ranging from (zero) 0 to (nine) 9.

Functions used to remove numbers from a string in Java

.replaceAll(“to_be_replaced”,”replace_with”)

which can be used to replace all values of the variable “to_be_replaced” with the values of “replace_with”

Deletion of digits :

 

import java.util.Scanner;
class deletion
{
  public static void main(String[] args)
  {
    Scanner sc = new Scanner(System.in);
    String inp; // Variable 'inp',for storing the input
    System.out.println("Enter your string:");
    inp = sc.nextLine();
    System.out.println("After deletion of any digits,the string is:");
    inp = inp.replaceAll("[0123456789]",""); // .replaceAll(),function used to replace. 
    System.out.println(inp);
}
}

Output:

Enter your string:

Input

 "The decimal numbers will be deleted: 1973"

Output :

"After deletion of any digits, the string is:
The decimal numbers will be deleted: "

Summary :

Removal of any Digit is a quite an easy program in java; First we import the Scanner class using

import java.util.Scanner;

The Scanner class will help us take the input from the user. We take input and store it in variable ‘inp’. Then print out a line of  “After deletion of any digits, the string is:” which is nothing apart from a Good Practice, it can be omitted if the programmer wishes to. We then use the .replaceAll() command to replace the occurrence of any decimal digits in the inputted String.
we finally print out the String which has been cleaned of any digit in its body.

learn more:

Leave a Reply

Your email address will not be published. Required fields are marked *