Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the most clojuresque way to compare characters and string? (single char string)

I was wondering about which is the best (clojuresque) way to compare a character and a string in Clojure. Obviously something like that returns false:

(= (first "clojure") "c") 

because first returns a java.lang.Character and "c" is a single character string. Does exists a construct to compare directly char and string without invoking a cast? I haven't found a way different from this:

(= (str (first "clojure")) "c") 

but I'm not satisfied. Any ideas? Bye, Alfredo

like image 691
Alfredo Di Napoli Avatar asked Oct 19 '10 17:10

Alfredo Di Napoli


People also ask

Can you compare string char?

strcmp is used to compare two different C strings. When the strings passed to strcmp contains exactly same characters in every index and have exactly same length, it returns 0. For example, i will be 0 in the following code: char str1[] = "Look Here"; char str2[] = "Look Here"; int i = strcmp(str1, str2);

Can I use == to compare char?

Yes, char is just like any other primitive type, you can just compare them by == .

Can you compare a string and a char in Java?

Object Oriented Programming FundamentalsYou can compare two Strings in Java using the compareTo() method, equals() method or == operator. The compareTo() method compares two strings. The comparison is based on the Unicode value of each character in the strings.


2 Answers

How about the straight forward String interop?

(= (.charAt "clojure" 0) \c)

or

(.startsWith "clojure" "c")

It should be as fast as it can get and doesn't allocate a seq object (and in your second example an additional string) which is immediately thrown away again just to do a comparison.

like image 183
kotarak Avatar answered Sep 21 '22 08:09

kotarak


Character literals are written \a \b \c ... in Clojure so you can simply write

(= (first "clojure") \c) 
like image 20
Jonas Avatar answered Sep 25 '22 08:09

Jonas