简体   繁体   中英

Java String/Char charAt() Comparison

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.

// 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. eg '9' is character (char) 57 This comparison is true for any character less than the code for 9 eg space.

在此输入图像描述

The first character of your string is 'a' which is (char) 97 so (char) 97 < (char) 57 is false.

String str = "asdf";
String output = " ";
if(str.charAt(0) == '-'){
  // What does it mean when it's equal to '-'?
  output= "- exists in the first index of the String";
}
else {
    output="- doesn't exists in the first index of the String"; 
}
System.out.println(output);

It checks if that char exists in index 0, it is a comparison.

As for if (c < '9') , the ascii values of c and 9 are compared. I don't know why you would check if ascii equivalent of c is smaller than ascii equivalent of '9' though.

If you want to get ascii value of any char, then you can:

char character = 'c';
int ascii = character;
System.out.println(ascii);

str.charAt(0) == '-'; returns a boolean , in this case false .

if (c < '9') compares ascii value of '3' with ascii value of '9' and return boolean again.

str.charAt(0) == '-'

This statement returns a true if the character at point 0 is '-' and false otherwise.

if (c < '9')

This compares the ascii value of c with the ascii value of '9' in this case 99 and 57 respectively.

Characters are a primitive type in Java, which means it is not a complex object. As a consequence, every time you're making a comparison between chars , you are directly comparing their values.

Java characters are defined according to the original unicode specification, which gives each character a 16-bit value. These are the values that Java is comparing when you are comparing something like c>'3' or str.charAt(0) == '-' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM