集册 Java实例教程 将字符串与内置方法进行比较

将字符串与内置方法进行比较

欢马劈雪     最近更新时间:2020-01-02 10:19:05

589
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用内置的equals(),equalsIgnoreCase(),compareTo()和compareToIgnoreCase()方法来比较String值。

public class Main {

    public static void main(String[] args){

        String one = "one";

        String two = "two";// 来 自 n  o  w  j  a  v  a . c o m


        String var1 = "one";

        String var2 = "Two";


        String pieceone = "o";

        String piecetwo = "ne";

        

        if (one.equals(var1)){

            System.out.println ("String one equals var1 using equals");

        }
        /* 
         来自 
        *nowjava.com*/


        if (one.equals(two)){

            System.out.println ("String one equals two using equals");

        }


        if (two.equals(var2)){

            System.out.println ("String two equals var2 using equals");

        }


        if (one == var1){

            System.out.println ("String one equals var1 using ==");

        }


        if (two.equalsIgnoreCase(var2)){

            System.out.println ("String two equals var2 using equalsIgnoreCase");

        }


        System.out.println("Trying to use == on Strings that are pieced together");


        String piecedTogether = pieceone + piecetwo;


        if (one.equals(piecedTogether)){

            System.out.println("The strings contain the same value using equals");

        }


        if (one == piecedTogether) {

            System.out.println("The string contain the same value using == ");

        }


        if (one.compareTo(var1) == 0){

            System.out.println("One is equal to var1 using compareTo()");

        }

        

        System.out.println("Comparision Using regionMatches");


        String sentence = "Java 8 is great!";

        String matchStr = 
展开阅读全文