8

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.

2 Answers 2

14

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")
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, this is what i was looking out for. now i can see i can use java api of String class by using (. ), i tried (subs "swapbil" 1 4) and (. "swapnil" substring 1 4) both gives ans wap , is there any performance degrade if i use java in clojure? or both will have same performance.
I imagine that the performance should be comparable. You can build a quick micro-benchmark if you are worried.
In general the only performance penalty you might suffer using Java in Clojure is the use of reflection to look up a method at runtime if an object's class can't be inferred at compile-time. The clojure.string functions all use type hints to avoid reflection, so there should be negligible performance difference between the Clojure and Java versions.
Thanks for the improvement @kotarak.
@EmilSit You are welcome. In fact the new notation is translated to the old one. And in macros the old one is quite useful at times. However in the source the new one looks more clojurey. Similar: (Constructor. a b c) vs. (new Constructor a b c)
6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.