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
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);
Yes, char is just like any other primitive type, you can just compare them by == .
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.
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.
Character literals are written \a \b \c ...
in Clojure so you can simply write
(= (first "clojure") \c)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With