How to convert a clojure string of numbers into separate integers?

Does this 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)

In case the Clojure version you're using doesn't have clojure.string namespace you can skip the use command and define the function in a following way.

(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.


Works for all numbers and returns nil in the case it isn't a number (so you can filter out nils 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)))

E.g.

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

Tags:

Clojure