Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #221 Remove all non-digits characters

Create string t from string s, keeping only digit characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

import static java.lang.Character.isDigit;
String t = "";
for (char c : s.toCharArray())
    if (isDigit(c)) t = t + c;
import static java.lang.Character.isDigit;
String t = "";
char c;
int i, n = s.length();
for (i = 0; i < n; ++i)
    if (isDigit(c = s.charAt(i)))
        t = t + c;
import static java.lang.String.valueOf;
import static java.util.stream.Collectors.joining;
String t = s.chars()
    .filter(Character::isDigit)
    .mapToObj(x -> valueOf((char) x))
    .collect(joining());
String t = s.replaceAll("\\D+", "");
StringBuilder tb = new StringBuilder();
for (int i=0; i<s.length(); i++){
    if(Character.isDigit(s.charAt(i)))
        tb.append(s.charAt(i));
}
String t = tb.toString();
(require '[clojure.string :as str])
(let [s "1a22b3c4de5f6"
      t (str/replace s #"[^\d]" "")]
  (println t))

Uses a regex to get only the digit characters.

New implementation...