Search code examples
stringclojurecase-sensitive

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"

Solution

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