开发者

Clojure to remove non-numbers from a string

开发者 https://www.devze.com 2023-03-07 00:05 出处:网络
I have the following code to try to remove non-numbers fromastring: (apply str (flatten (map (fn[x] (if (number? x) x))

I have the following code to try to remove non-numbers froma string:

(apply str 
    (flatten 
        (map 
            (fn[x] 
                (if (number? x) x)) 
                "ij443kj"
        )
    )
)

But it always returns an empty string instead of "443". Doe开发者_如何学JAVAs anyone know what I am doing wrong here and how I can get the desired result?


number? doesn't work that way. It checks the type. If you pass it a character, you'll get back false every time, no matter what the character is.

I'd probably use a regular expression for this, but if you want to keep the same idea of the program, you could do something like

(apply str (filter #(#{\0,\1,\2,\3,\4,\5,\6,\7,\8,\9} %) "abc123def"))

or even better

(apply str (filter #(Character/isDigit %) myString))


There is an even simpler way, use a regular expression:

(.replaceAll "ij443kj" "[^0-9]" "")


get the char's int values...

(map int (apply vector "0123456789"))

-> (48 49 50 51 52 53 54 55 56 57)

then fix it:

(defn my-int
[char]
(- (int char) 48))

now let's try this again, shall we?

(map my-int (apply vector "0123456789"))

-> (0 1 2 3 4 5 6 7 8 9)

and just to get a warm-and-fuzzy that they're integers...

(map #(* % 10) (map my-int (apply vector "0123456789")))

-> (0 10 20 30 40 50 60 70 80 90)

(reduce + (map my-int (apply vector "0123456789")))

-> 45


in case you will handling decimal

#(re-seq #"[0-9\.]+" "ij443kj")
0

精彩评论

暂无评论...
验证码 换一张
取 消