Java中如何比较字符
时间:2020-02-23 14:34:45 来源:igfitidea点击:
在本文中,我们将在Java中比较字符。
Java提供了一些内置方法 compare()和 equals()比较字符对象。
虽然,我们可以使用少于或者大于运算符,但它们仅适用于原始值。
让我们拍一些例子来比较Java中的字符。
比较原始字符
我们可以使用使用的原始字符 Character.compare()方法或者 <,>或者 =关系运算符。
使用compare()
这 compare()字符类的方法返回正数值,负或者零。
请参阅下面的示例。
class Main {
public static void main(String[] args){
char a = 'a';
char b = 'b';
if(Character.compare(a, b) > 0) {
System.out.println("a is greater");
}else if(Character.compare(a, b) < 0) {
System.out.println("a is less than b");
}else
System.out.println("Both are equal");
}
}
输出
a is less than b
使用关系运算符
我们可以使用少于或者大于比较Java中的两个字符的关系运算符。
它是最简单的方法,不涉及任何类别或者方法。
class Main {
public static void main(String[] args){
char a = 'a';
char b = 'b';
if(a > b) {
System.out.println("a is greater");
}else if(a < b) {
System.out.println("a is less than b");
}else
System.out.println("Both are equal");
}
}
输出
a is less than b
比较字符对象
我们可以使用使用的原始字符 Character.compare()方法或者 equals()方法。
使用compare()
我们可以使用 compare()具有字符对象的方法也是如此。
这 compare()字符类的方法返回正数值,负或者零。
请参阅下面的示例。
class Main {
public static void main(String[] args){
Character ch1 = 'x';
Character ch2 = 'y';
if(Character.compare(ch1, ch2) > 0) {
System.out.println("x is greater");
}else if(Character.compare(ch1, ch2) < 0) {
System.out.println("x is less than y");
}else
System.out.println("Both are equal");
}
}
输出
x is less than y
使用Equals()
这 equals()方法用于检查两个CHAR对象是否等于或者不等于。
它返回 true如果两者都等于其他回报 false。
class Main {
public static void main(String[] args){
Character a = 'a';
Character b = 'b';
if(a.equals(b)) {
System.out.println("a is equals b");
}else
System.out.println("a is not equal to b");
}
}
输出
a is not equal to b

