博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何在Java中比较字符串
阅读量:2526 次
发布时间:2019-05-11

本文共 15584 字,大约阅读时间需要 51 分钟。

字符串比较是编程中的一项基本操作,通常在面试中被测验。 这些字符串是不可变的字符序列,这意味着随着时间的过去不变或无法更改。

Java有许多比较字符串的方法。 本文将教您如何在Java中比较字符串的主要操作。

有六个选项:

  1. ==运算符
  2. 字符串等于
  3. 字符串equalsIgnoreCase
  4. 字符串compareTo
  5. 字符串compareToIgnoreCase
  6. 对象等于

==运算符

==是一个运算符,如果要比较的内容引用相同的内存,则返回true;否则,返回false 。 如果两个与==进行比较的字符串引用了相同的字符串内存,则返回值为true ; 如果不是,则为false

string1      
=
"MYTEXT"
;
string2
=
"YOURTEXT"
;
               
.
out .
println
(
"Output: "
+
( string1
== string2
)
)
;
Output
:
false

上面==的返回值为false ,因为“ MYTEXT”和“ YOURTEXT”引用了不同的内存。

string1      
=
"MYTEXT"
;
string6
=
"MYTEXT"
;
               
.
out .
println
(
"Output: "
+
( string1
== string6
)
)
;
Output
:
true

在这种情况下, ==的返回值为true ,因为编译器在内部为两个“ MYTEXT”存储器创建一个存储器位置,并且两个变量都引用相同的存储器位置。

string1      
=
"MYTEXT"
;
string7
= string1
;
.
out .
println
(
"Output: "
+
( string1
== string7
)
)
;
Output
:
true

如果猜对了,就知道string7的初始化位置与string1相同,因此==为true。

string1      
=
"MYTEXT"
;
string4
=
new
(
"MYTEXT"
)
;
.
out .
println
(
"Output: "
+
( string1
== string4
)
)
;
Output
:
false

在这种情况下,即使string4和string1的值相同,编译器也会创建一个新的内存位置。

string1      
=
"MYTEXT"
;
string5
=
new
( string1
)
;
.
out .
println
(
"Output: "
+
( string1
== string4
)
)
;
Output
:
false

在这里,string5是一个用string1初始化的新字符串对象; 因此, string1 == string4不正确。

字符串等于

字符串类具有String equals方法,用于比较两个字符串。 与equals的字符串比较区分大小写。 根据 :

    /**     
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)
     */
    public boolean equals(Object anObject) { ... }

让我们看几个例子:

string1      
=
"MYTEXT"
;
string2
=
"YOURTEXT"
;
.
out .
println
(
"Output: "
+ string1.
equals
( string2
)
)
;
Output
:
false

如果字符串不相同,则equals方法的输出显然为false

string1      
=
"MYTEXT"
;
string3
=
"mytext"
;
.
out .
println
(
"Output: "
+ string1.
equals
( string3
)
)
;
Output
:
false

这些字符串的值相同,但大小写不同。 因此,输出为false

string1      
=
"MYTEXT"
;
string4
=
new
(
"MYTEXT"
)
;
.
out .
println
(
"Output: "
+ string1.
equals
( string4
)
)
;
Output
:
true
string1      
=
"MYTEXT"
;
string5
=
new
( string1
)
;
.
out .
println
(
"Output: "
+ string1.
equals
( string5
)
)
;
Output
:
true

这两种情况下的示例均为true ,因为两个值相同。 与==不同,上面的第二个示例返回true

调用equals的字符串对象显然应该是有效的字符串对象,并且不能为null。

string1      
=
"MYTEXT"
;
string8
=
null
;
.
out .
println
(
"Output: "
+ string8.
equals
( string1
)
)
;
in thread _____  java.
lang .

上面显然不是一个好的代码。

.      
out .
println
(
"Output: "
+ string1.
equals
( string8
)
)
;
Output
:
false

没关系

字符串equalsIgnoreCase

equalsIgnoreCase的行为与equals相同, 只是有一个区别-比较不区分大小写。 说:

    /**     
     * Compares this {@code String} to another {@code String}, ignoring case
     * considerations.  Two strings are considered equal ignoring case if they
     * are of the same length and corresponding characters in the two strings
     * are equal ignoring case.
     *
     *

Two characters {@code c1} and {@code c2} are considered the same

     * ignoring case if at least one of the following is true:
     *

         *  
  • The two characters are the same (as compared by the
         *        {@code ==} operator)
         *  
  • Applying the method {@link
         *        java.lang.Character#toUpperCase(char)} to each character
         *        produces the same result
         *  
  • Applying the method {@link
         *        java.lang.Character#toLowerCase(char)} to each character
         *        produces the same result
         *
     *
     * @param  anotherString
     *         The {@code String} to compare this {@code String} against
     *
     * @return  {@code true} if the argument is not {@code null} and it
     *          represents an equivalent {@code String} ignoring case; {@code
     *          false} otherwise
     *
     * @see  #equals(Object)
     */
    public boolean equalsIgnoreCase(String anotherString) { ... }

equals (上面)中的第二个示例是equalsIgnoreCase与比较中的唯一区别。

string1      
=
"MYTEXT"
;
string3
=
"mytext"
;
.
out .
println
(
"Output: "
+ string1.
equalsIgnoreCase
( string3
)
)
;
Output
:
true

由于比较不区分大小写,因此返回trueequals下的所有其他示例与equalsIgnoreCase相同。

字符串compareTo

compareTo方法按字典顺序(即,属于字母顺序)和区分大小写地比较两个字符串,并返回两个字符串的字典差异。 该将词典顺序计算描述为:

/**     
     * Compares two strings lexicographically.
     * The comparison is based on the Unicode value of each character in
     * the strings. The character sequence represented by this
     * {@code String} object is compared lexicographically to the
     * character sequence represented by the argument string. The result is
     * a negative integer if this {@code String} object
     * lexicographically precedes the argument string. The result is a
     * positive integer if this {@code String} object lexicographically
     * follows the argument string. The result is zero if the strings
     * are equal; {@code compareTo} returns {@code 0} exactly when
     * the {@link #equals(Object)} method would return {@code true}.
     *

     * This is the definition of lexicographic ordering. If two strings are
     * different, then either they have different characters at some index
     * that is a valid index for both strings, or their lengths are different,
     * or both. If they have different characters at one or more index
     * positions, let k be the smallest such index; then the string
     * whose character at position k has the smaller value, as
     * determined by using the < operator, lexicographically precedes the
     * other string. In this case, {@code compareTo} returns the
     * difference of the two character values at position {@code k} in
     * the two string -- that is, the value:
     *

     
     * this.charAt(k)-anotherString.charAt(k)
     *
     * If there is no index position at which they differ, then the shorter
     * string lexicographically precedes the longer string. In this case,
     * {@code compareTo} returns the difference of the lengths of the
     * strings -- that is, the value:
     *
     
     * this.length()-anotherString.length()
     *
     *
     * @param   anotherString   the {@code String} to be compared.
     * @return  the value {@code 0} if the argument string is equal to
     *          this string; a value less than {@code 0} if this string
     *          is lexicographically less than the string argument; and a
     *          value greater than {@code 0} if this string is
     *          lexicographically greater than the string argument.
     */
    public int compareTo(String anotherString) { ... }

让我们看一些例子。

string1      
=
"A"
;
string2
=
"B"
;
.
out .
println
(
"Output: "
+ string1.
compareTo
( string2
)
)
;
Output
:
-
1
.
out .
println
(
"Output: "
+ string2.
compareTo
( string1
)
)
;
Output
:
1
string1      
=
"A"
;
string3
=
"a"
;
.
out .
println
(
"Output: "
+ string1.
compareTo
( string3
)
)
;
Output
:
-
32
.
out .
println
(
"Output: "
+ string3.
compareTo
( string1
)
)
;
Output
:
32
string1      
=
"A"
;
string6
=
"A"
;
               
        .
out .
println
(
"Output: "
+ string1.
compareTo
( string6
)
)
;
Output
:
0
String string1 = "A";     
String string8 = null;
               
System.out.println("Output: " + string8.compareTo(string1));
Exception in thread ______  java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1155)
String string1 = "A";
String string10 = "";
               
System.out.println("Output: " + string1.compareTo(string10));
Output: 1

字符串compareToIgnoreCase

与compareToIgnoreCase的行为是与一个差相同的compareTo:琴弦不考虑情况下进行比较。

string1      
=
"A"
;
string3
=
"a"
;
.
out .
println
(
"Output: "
+ string1.
compareToIgnoreCase
( string3
)
)
;
Output
:
0

对象等于

Objects equals方法调用覆盖的String equals方法; 其行为与上述“ 字符串等于”示例中的行为相同。

string1      
=
"MYTEXT"
;
string2
=
"YOURTEXT"
;
.
out .
println
(
"Output: "
+ Objects
( string1, string2
)
)
;
Output
:
false
string1      
=
"MYTEXT"
;
string3
=
"mytext"
;
.
out .
println
(
"Output: "
+ Objects
( string1, string3
)
)
;
Output
:
false
string1      
=
"MYTEXT"
;
string6
=
"MYTEXT"
;
.
out .
println
(
"Output: "
+ Objects
( string1, string6
)
)
;
Output
:
true
string1      
=
"MYTEXT"
;
string8
=
null
;
.
out .
println
(
"Output: "
+ Objects.
equals
( string1, string8
)
)
;
Output
:
false
.
out .
println
(
"Output: "
+ Objects.
equals
( string8, string1
)
)
;
Output
:
false
string8      
=
null
;
string9
=
null
;
.
out .
println
(
"Output: "
+ Objects.
equals
( string8, string9
)
)
;
Output
:
true

这样做的好处是Objects equals方法检查空值(与String equals不同)。 对象等于的实现是:

public      
static
boolean equals
( a, b
)
{
return
( a
== b
)
||
( a
!=
null
&& a.
equals
( b
)
)
;
}

使用哪种方法?

有很多方法可以比较两个字符串。 您应该使用哪一个? 通常,对区分大小写的字符串使用String等于 ,对不区分大小写的比较使用String equalsIgnoreCase 。 但是,请注意:如果一个或两个字符串为null,则要注意NPE( NullPointerException )。

源代码可在和 。

翻译自:

转载地址:http://oqizd.baihongyu.com/

你可能感兴趣的文章
uml与数据库设计
查看>>
sqlplus
查看>>
.net 中文语音朗读
查看>>
asp.net 生成图形验证码(字母和数字混合)
查看>>
ajax分页效果、分类联动、搜索功能
查看>>
linux 下使用 tc 模拟网络延迟和丢包
查看>>
Bootstrap 教程 之 Less 入门文档
查看>>
期望dp+高斯消元——bzoj3143
查看>>
iOS开发UI篇—使用storyboard创建导航控制器以及控制器的生命周期
查看>>
ValueStack中的context与ActionContext的区别
查看>>
mysql学习笔记4
查看>>
Lua的元方法__newindex元方法
查看>>
Java-笔记10
查看>>
微服务2.0时代,论其痛点与触点
查看>>
Java中高级面试必问之多线程TOP50(含答案)
查看>>
mybatis中&gt;=和&lt;=的实现方式
查看>>
@ResponseBody与@RestController的作用与区别
查看>>
罗胖又有“惊人之语”:内容收费的窗口期正来到
查看>>
js自定义对象
查看>>
背包九讲-第三讲 多重背包
查看>>