Ask Question
20 July, 17:35

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.

+1
Answers (1)
  1. 20 July, 21:26
    0
    public static String onlyDigits (String in) {

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

    return digitsOnly;

    }

    A Complete program is wrtten in the explanation section

    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
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a Java method onlyDigits that takes a string as a parameter. The method should remove from the string all characters, which are not ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers