How to convert clojure string of numbers to single integers?

I can read some data like this in repl. For a real program, I plan to assign a special let form.

(def x1 (line-seq (BufferedReader. (StringReader. x1)))) 

If I enter 5 5, x1 is attached to ("5 5")

I would like to convert this list of one element to a list of two integers. How can i do this? I played with parsing a string in a space, but it's hard for me to convert to integer.

+6
source share
2 answers

Does it help? In Clojure 1.3.0:

 (use ['clojure.string :only '(split)]) (defn str-to-ints [string] (map #(Integer/parseInt %) (split string #" "))) (str-to-ints "5 4") ; => (5 4) (apply str-to-ints '("5 4")) ; => (5 4) 

If the version of Clojure you are using does not have the clojure.string namespace, you can skip the use command and define the function as follows.

 (defn str-to-ints [string] (map #(Integer/parseInt %) (.split #" " string))) 

You can get rid of regular expressions by using (.split string " ") in the last line.

+6
source

It works for all numbers and returns zero if it is not a number (so you can filter the zeros in the resulting seq)

 (require '[clojure.string :as string]) (defn parse-number "Reads a number from a string. Returns nil if not a number." [s] (if (re-find #"^-?\d+\.?\d*$" s) (read-string s))) 

eg.

 (map parse-number (string/split "1 2 3 78 90 -12 0.078" #"\s+")) ; => (1 2 3 78 90 -12 0.078) 
+3
source

Source: https://habr.com/ru/post/903406/


All Articles