JAVA——特殊类(1)——String类(3)——字符串比较(方法)

(二)字符串比较

在这里插入图片描述

  • (1)比较字符串是否相等——区分大小写——返回值为Boolean型

public boolean equals(Object anObject)
//anObject——传入需要被比较的对象
//此方法区分大小写
  • (2)比较字符串是否相等——不区分大小写——返回值为Boolean型
public boolean equalsIgnoreCase(String anotherString)
//anObject——传入需要被比较的对象
//此方法不区分大小写

对(1)(2)同时举例如下:

public class TestString11_20{
	public static void main(String[] args){
		String str1 = "hello";
		String str2 = "Hello";
       //区分大小写的比较
		System.out.println(str1.equals(str2));//false

      //不区分大小写的比较
		System.out.println(str1.equalsIgnoreCase(str2));//true
	}
}

运行结果如下:
在这里插入图片描述

  • (3)比较两个字符串的大小关系——返回值为int型,
    返回0 或 大于0的数 或 小于0 的数;
    区分大小写。


    返回值只有三种结果:
  1. 相等:返回0
  2. 大于:返回大于0的值
  3. 小于:返回小于0的值

public int compareTo(String anotherString)
//传入需要被比较的参数对象

举例如下:

//大写字母的值 + 32 = 小写字母的值
public class TestString11_20{
	public static void main(String[] args){
		String str1 = "a";
		String str2 = "A";
		System.out.println(str1.compareTo(str2));
	}
}

运行结果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/xmfjmcwf/article/details/84323352