Skip to content

Latest commit

 

History

History
131 lines (88 loc) · 2.93 KB

214.md

File metadata and controls

131 lines (88 loc) · 2.93 KB

Java 程序:比较字符串

原文: https://www.programiz.com/java-programming/examples/compare-strings

在此程序中,您将学习比较 Java 中的两个字符串。

示例 1:比较两个字符串

public class CompareStrings {

    public static void main(String[] args) {

        String style = "Bold";
        String style2 = "Bold";

        if(style == style2)
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
    }
}

运行该程序时,输出为:

Equal

在上面的程序中,我们有两个字符串stylestyle2。 我们仅使用相等运算符(==)比较两个字符串,这会将值BoldBold进行比较,并输出Equal


示例 2:使用equals()比较两个字符串

public class CompareStrings {

    public static void main(String[] args) {

        String style = new String("Bold");
        String style2 = new String("Bold");

        if(style.equals(style2))
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
    }
}

运行该程序时,输出为:

Equal

在上面的程序中,我们有两个字符串stylestyle2都包含相同的全局Bold

但是,我们使用了String构造器来创建字符串。 要在 Java 中比较这些字符串,我们需要使用字符串的equals()方法。

您不应该使用==(相等运算符)来比较这些字符串,因为它们会比较字符串的引用,即它们是否是同一对象。

另一方面,equals()方法比较字符串的值是否相等,而不是对象本身。

如果改为将程序更改为使用等号运算符,则会显示Not Equal,如下所示。


示例 3:使用==比较两个字符串对象(不起作用)

public class CompareStrings {

    public static void main(String[] args) {

        String style = new String("Bold");
        String style2 = new String("Bold");

        if(style == style2)
            System.out.println("Equal");
        else
            System.out.println("Not Equal");
    }
}

运行该程序时,输出为:

Not Equal

示例 4:比较两个字符串的不同方法

这是在 Java 中可能进行的字符串比较。

public class CompareStrings {

    public static void main(String[] args) {

        String style = new String("Bold");
        String style2 = new String("Bold");

        boolean result = style.equals("Bold"); // true
        System.out.println(result);

        result = style2 == "Bold"; // false
        System.out.println(result);

        result = style == style2; // false
        System.out.println(result);

        result = "Bold" == "Bold"; // true
        System.out.println(result);
    }
}

运行该程序时,输出为:

true
false
false
true