Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether string ends with given string in clojure

Tags:

string

clojure

I have created a function to check whether or not my first string ends with a second string.

In Java we have ready made method to check this, but in Clojure I failed to find such a method so I written custom function as follows:

(defn endWithFun [arg1 arg2] 
    (= (subs arg1 (- (count arg1) (count arg2)) (count arg1)) arg2))

Outputs:

> (endWithFun "swapnil" "nil")
true
> (endWithFun "swapnil" "nilu")
false

This is working as expected.

I want to know, is there a similar alternative? Also in my case, I compare case sensitively. I also want to ignore case sensitivity.

like image 529
swapy Avatar asked Jul 30 '13 03:07

swapy


2 Answers

You can access the native Java endsWith directly in Clojure:

(.endsWith "swapnil" "nil")

See http://clojure.org/java_interop for some more details.

You can then naturally compose this to get case insensitivity:

(.endsWith (clojure.string/lower-case "sWapNIL") "nil")
like image 54
Emil Sit Avatar answered Oct 21 '22 10:10

Emil Sit


Clojure 1.8 introduced an ends-with? function in clojure.string, so now there is a native function:

> (ends-with? "swapnil" "nil")
true
> (ends-with? "swapnil" "nilu")
false

Again, just apply lower-case if you want case insensitivity.

like image 29
Brad Koch Avatar answered Oct 21 '22 09:10

Brad Koch