Java为我们供应了compareTo、“==”、equals对字符串举行比较,下面引见一下他们的区分。
示例一:compareTo比较数据的大小 (引荐进修:java课程)
compareTo(string) compareToIgnoreCase(String) compareTo(object string)
该示例经由过程运用上面的函数比较两个字符串,并返回一个int范例。若字符串即是参数字符串、则返回0,字符串小于参数字符串、则返回值小于0,字符串大于参数字符串、返回值大于0。
推断字符串大小的依据是依据他们在字典中的递次决议的。
package com.de.test; /** * Java字符串比较大小 */ public class StringA { public static void main(String[] args){ String str = "String"; String anotherStr = "string"; Object objstr = str; System.out.println(str.compareTo(anotherStr)); System.out.println(str.compareToIgnoreCase(anotherStr)); System.out.println(str.compareTo(objstr.toString())); } }
实行上面代码发生下面效果
-32 0 0
示例二:运用equals(),“==”体式格局比较字符串
运用equals()和==,区分在于equals比较的是内容是不是相称、==比较的是援用的变量地点是不是相称。
package com.de.test; public class StringA { public static void main(String[] args){ String s1 = "hello"; String s2 = "hello"; String s3 = new String("hello"); String s4 = new String("hello"); System.out.println("s1:" + s1); System.out.println("s2:" + s2); System.out.println("s3:" + s3); System.out.println("s4:" + s4); System.out.println("----------比较内容是不是相称---------------"); System.out.println(s1.equals(s2)); System.out.println(s2.equals(s3)); System.out.println(s3.equals(s4)); System.out.println("----------比较援用地点是不是相称---------------"); System.out.println(s1 == s2); System.out.println(s2 == s3); System.out.println(s3 == s4); } }
实行上面代码发生下面效果
s1:hello s2:hello s3:hello s4:hello ----------比较内容是不是相称--------------- true true true ----------比较援用地点是不是相称--------------- true false false
以上就是java怎样举行字符串的比较的细致内容,更多请关注ki4网别的相干文章!