如何在Java中比较两个字符串的元素?

huangapple go评论145阅读模式
英文:

How to compare two elements of a string in Java?

问题

请帮忙了解如何在Java中比较两个字符串元素。我可以在C/C++中通过string[i] == string[j]这样简单地实现。但是当我在Java中像C/C++一样比较两个字符串元素时,我的IDE显示错误。

代码:

String username = scanner.nextLine();
scanner.close();
int count = 0;
for (int i = 0; i < username.length() - 1; i++)
{
    for (int j = i + 1; j < username.length(); j++) 
    {
        if (username.charAt(i) == username.charAt(j))  // 错误出现在这里
        {
            count++;
            break;
        }
    }
}

谢谢。

英文:

Please help to know how to compare two elements of a string in java. I can do it in C/C++ simply by string[i] == string[j] this way. But my ide is showing error when I compare two elements of a string in java like c/c++.

Code:

String username = scanner.nextLine();
        scanner.close();
        int count = 0;
        for (int i = 0; i &lt; username.length() - 1; i++)
        {
            for (int j = i + 1; j &lt; username.length(); j++) 
            {
                if (username[i] == username[j])  // Error is here
                {
                    count++;
                    break;
                }
            }
        }

Thank you.

答案1

得分: 1

string.charAt(i) == string.charAt(j)

字符串是对象而不是数组。

英文:

string.charAt(i) == string.charAt(j)

Strings are objects not arrays

答案2

得分: 1

如果您想在Java中比较字符串的两个字符,要访问这些字符,您必须使用字符串函数charAt(index)
针对上述问题的解决方案如下:

username.charAt(i) == username.charAt(j)
英文:

If you want to compare 2 characters of String in java, for accessing those characters you have to use String function charAt(index).
For the above problem solution goes like this:

username.charAt(i) == username.charAt(j)

答案3

得分: 1

在Java中,字符串拥有它们专属的String类型,它不是数组,因此您不能使用方括号访问其字符。相反,您应该使用String方法来比较两个字符串或访问它们的字符。要进行字符串比较,请使用equals()方法:

aString.equals(anotherString);

要访问字符串的字符,请使用charAt()方法:

"Hello!".charAt(1); // 返回 'e'
英文:

In Java strings have their dedicated type String which is not an Array, so you can't access its characters with squared brackets. Instead, you should use String methods to compare 2 strings or access their characters. For string comparison use equals():

aString.equals(anotherString)

To access string's characters use charAt​(...):

&quot;Hello!&quot;.charAt​(1); // returns &#39;e&#39;

答案4

得分: 1

对于引用数据类型,比如String,== 比较的是两个对象的引用地址,也就是内存地址是否相同。如果内存地址相同,那么它们自然是同一个对象。同一个对象之间的比较是怎样的呢?

我们一般的应用场景主要是比较两个String对象的内容,这时我们需要使用 equals() 方法。我们可以看一下在 java.lang.Stringequals() 方法的定义,可以看到 equals() 方法是在比较两个String对象的值。


/**
* 将此字符串与指定对象进行比较。仅当参数不为{@code null},并且是表示与此对象相同字符序列的{@code String}对象时,结果才为{@code true}。
*
* @param  anObject
*         要与此{@code String}进行比较的对象
*
* @return  如果给定的对象表示与此字符串相等的{@code String},则为{@code true},否则为{@code false}
*
* @see  #compareTo(String)
* @see  #equalsIgnoreCase(String)
*/
public Boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                                    return false;
                i++;
            }
            return true;
        }
    }
    return false;

还有一个特殊情况,比如 &quot;abcde&quot; == &quot;abcde&quot; 或者 &quot;abcde&quot; == &quot;abc&quot; + &quot;de&quot; 都会返回true,因为这两种情况都是由编译器直接实现的,没有被声明为变量。

当然,如果你知道自己在做什么,并且想要充分利用 == 的特性,那么自然也没有问题。在其他时候,使用 equals() 方法。

英文:

For reference data types like String, == compares the reference addresses of two objects, that is, whether the memory addresses are the same. If the memory addresses are the same, it is naturally the same object. What is the comparison between the same objects.

Our general application scenario is mainly to compare the contents of two String objects, then we need to use the equals() method. We can look at the definition of equals() method in java.lang.String, we can see that equals() is comparing the values of two String objects


/**
* 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) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                                    return false;
                i++;
            }
            return true;
        }
    }
    return false;

There is also a special case, such as &quot;abcde&quot; == &quot;abcde&quot; or &quot;abcde&quot; == &quot;abc&quot; + &quot;de&quot; will both return true, because both are directly implemented by the compiler and have not been Declared as a variable.

Of course, if you know what you are doing, you have to take advantage of this feature of ==, naturally there is no problem. At other times, use equals() method.

huangapple
  • 本文由 发表于 2020年7月24日 21:30:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63074596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定