sfactor
sfactor

Reputation: 13062

How to compare the case of two strings in Clojure?

I have a Clojure function autocomplete that takes in a prefix and returns the possible autocompletion of that string. For example, if the input is abs, I get absolute as the possible complete word.

The problem is that the function does a case-insentitive match for the prefix so if I have Abs as the prefix input, I still get absolute instead of Absolute.

What would be the correct way to get the final string completion that matches the case of the original prefix entered?

So, a function case-match that could work like

(case-match "Abs" "absolute")  => "Absolute"

Upvotes: 1

Views: 769

Answers (2)

fl00r
fl00r

Reputation: 83680

also, you can go with startsWith

(defn case-match
  [prefix s]
  (when (.startsWith (clojure.string/lower-case s)
                     (clojure.string/lower-case prefix))
       s))

(case-match "Abs" "absolute")
#=> "absolute"
(case-match "Absence" "absolute")
#=> nil

Upvotes: 0

Taylor Wood
Taylor Wood

Reputation: 16194

You can use the prefix string as the prefix to the case-insensitive search result. Just use subs to drop the length of the prefix from the search result:

(defn case-match [prefix s]
  (str prefix (subs s (count prefix))))

(case-match "Abs" "absolute")
=> "Absolute"

This assumes your autocomplete function stays separate, and case-match would be applied to its result.

Upvotes: 3

Related Questions