首页 > 代码库 > 比较字符串

比较字符串

1、判断字符串是否相等

有equals方法和equalsIgnoreCase,前者区分大小写,后者不区分大小写

使用==符号比较字符串时,比较的是字符串的地址,不是内容

 1 import javax.print.DocFlavor.STRING;
 2 
 3 public class Opinion {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         String s1 = new String("I am a student");
 8         String s2 = new String("I am a student");
 9         String s3 = new String("I AM A STUDENT");
10         String s4 = s1;
11         
12         boolean b1=(s1==s2);//在字符串中间用"=="比较的是内存的位置,不适合拿来比较字符串
13         boolean b2=(s1==s4);//这里s1和s4的地址相同,内容也相同
14         boolean b3=s1.equals(s2);
15         boolean b4=s1.equals(s3);//equals区分大小写
16         boolean b5=s1.equalsIgnoreCase(s2);
17         boolean b6=s1.equalsIgnoreCase(s3);
18         
19         System.out.println("s1==s2:"+b1);
20         System.out.println("s1==s4:"+b2);
21         System.out.println("s1 equals s2:"+b3);
22         System.out.println("s1 equals s3:"+b4);
23         System.out.println("s1 equalsIgnoreCase s2:"+b5);
24         System.out.println("s1 equalsIgnoreCase s3:"+b6);
25         
26     }
27 
28 }

技术分享

 2、判断字符串的开始和结尾

startsWith和endsWith方法用来判断字符串是否以指定的内容开始和结束

 1 public class StartOrEnd {
 2 
 3     public static void main(String[] args) {
 4         // TODO Auto-generated method stub
 5         String num1 = "22012245560";
 6         String num2 = "41245463456";
 7 
 8         boolean b1 = num1.startsWith("22");
 9         boolean b2 = num1.endsWith("56");
10         boolean b3 = num2.startsWith("22");
11         boolean b4 = num2.endsWith("56");
12 
13         System.out.println("字符串num1是以‘22’开始的吗?" + b1);
14         System.out.println("字符串num1是以‘56’结束的吗?" + b2);
15         System.out.println("字符串num1是以‘22’开始的吗?" + b3);
16         System.out.println("字符串num1是以‘56’结束的吗?" + b4);
17 
18     }
19 
20 }

技术分享

 

比较字符串