第九课 字符串比较

第九课  字符串比较

在字符串比较时使用==做为比较方法和基本数据类型是不一样的,在JAVA中这种比较是比较两个字符串是否指向了同一个地址,而不会比较其中的内容,如果比较内容的话,我们需要以下的String提供的方法:
s1.compareTo(s2):如果S1大于S2则返回大于0的一个数;如果S1小于S2则返回小于0的一个数;如果S1等于S2,则返回0
s1.compareToIgnoreCase(s2):作用同上,不区分大小写
s1.equals(s2):如果两字符串相同返回真值,否则返回假值
s1.equalsIgnoreCase(s2):作用同上,不区分大小写
我们来看下面的例子:
public class StringDemo{
        public static void main(String args[]){
                String s1="this is a";
                String s2="this is a string";
                String s3;
                s3=s1;
               
                System.out.println("s1="+s1);
                System.out.println("s2="+s2);
                System.out.println("s3="+s3);
                System.out.println("s1==s3???"+(s1==s3));
                System.out.println("s1==s2???"+(s1==s2)+"/n");
               
                s1=s1+" string";    //s1指向了新的地址
                System.out.println("s1="+s1);
                System.out.println("s1==s3???"+(s1==s3));
                System.out.println("s1==s2???"+(s1==s2)+"/n");
                System.out.println("s1 equals s2????"+s1.equals(s2)+"/n");
               
                s2="This is a string";
                System.out.println("s2="+s2);
                System.out.println("s1 equals s2????"+s1.equals(s2)+"/n");//区分大小写
                System.out.println("s1 equals s2????"+s1.equalsIgnoreCase(s2)+"/n");//不区分大小写
               
                int result=s1.compareTo(s2);
                if (result>0)
                        System.out.println("S1 is greater than S2");
                else
                  if (result<0)
                    System.out.println("S1 is less than S2");
                  else
                    System.out.println("S1 is equal to S2");}}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章