Ask 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 digits, and return a string that contains only digits.

+2
Answers (1)
  1. 24 October, 08:52
    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?
Find 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 the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers