I have seen various comparisons that you can do with the charAt()
method.
However, I can't really understand a few of them.
String str = "asdf";
str.charAt(0) == '-'; // What does it mean when it's equal to '-'?
char c = '3';
if (c < '9') // How are char variables compared with the `<` operator?
Any help would be appreciated.
Object Oriented Programming Fundamentals You 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.
equals() is a method of all Java Objects. But char is not an Object type in Java, it is a primitive type, it does not have any method or properties, so to check equality they can just use the == equals operator.
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);
strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.
// What does it mean when it's equal to '-'?
Every letter and symbol is a character. You can look at the first character of a String and check for a match.
In this case you get the first character and see if it's the minus character. This minus sign is (char) 45
see below
// How are char variables compared with the
<
operator?
In Java, all characters are actually 16-bit unsigned numbers. Each character has a number based on it unicode. e.g. '9'
is character (char) 57
This comparison is true for any character less than the code for 9
e.g. space.
The first character of your string is 'a'
which is (char) 97
so (char) 97 < (char) 57
is false.
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