chris.fy
chris.fy

Reputation: 185

Clojure string searching and counting

I was wondering what the most Clojure-esque and standardised way of searching a string and returning boolean (or something falsy/truthy). (e.g In Java I would use .indexOf() and cast it to a boolean.)

What I want to do is search all the strings in a map and return 1 or 0, depending on whether the word "clouds" is in the string, and then find out the cumulative value at the end - I understand I can do this with regex, however I was wondering if there was an alternative?

Upvotes: 1

Views: 1075

Answers (1)

Michał Marczyk
Michał Marczyk

Reputation: 84331

Actually in Java the most natural solution is to use the contains method. You can do the same in Clojure:

(.contains "foobar" "bar")
;= true

Mapping over a seqable:

(mapv #(.contains "foobar" ^String %) ["foo" "bar"])
;= [true true]

With a map as input, you'd have to decide whether you want the keys, the values or both; depending on the answer, you'd want to use keys, vals or just map over the entries (in this case reduce-kv would yield a more performant solution than map).

This is assuming that you're searching for a literal substring (as with indexOf). With a regex, I'd use re-find and cast to boolean (it returns nil in absence of a match).

Upvotes: 3

Related Questions