165k views
3 votes
Write a Java method onlyDigits that takes a string as a parameter. The method should remove from the string all characters, which are not digits, and return a string that contains only digits.

User Artella
by
5.2k points

1 Answer

3 votes

Answer:

public static String onlyDigits(String in){

String digitsOnly = in.replaceAll("[^0-9]", "");

return digitsOnly;

}

A Complete program is wrtten in the explanation section

Step-by-step explanation:

public class TestClass {

public static void main(String[] args) {

String a = "-jaskdh2367sd.27askjdfh23";

System.out.println(onlyDigits(a));

}

public static String onlyDigits(String in){

String digitsOnly = in.replaceAll("[^0-9]", "");

return digitsOnly;

}

}

The output: 23672723

The main logic here is using the Java replaceAll method which returns a string after replacing all the sequence of characters that match its argument, regex with an empty string

User Kevin Wheeler
by
4.7k points