Ask Question
27 August, 23:43

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.

+3
Answers (1)
  1. 28 August, 00:24
    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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers