繁体   English   中英

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

[英]How to compare two elements of a string in Java?

请帮助了解如何比较 java 中字符串的两个元素。 我可以通过string[i] == string[j]这种方式在 C/C++ 中做到这一点。 但是,当我比较 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[i] == username[j])  // Error is here
                {
                    count++;
                    break;
                }
            }
        }

谢谢你。

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

字符串不是 arrays 的对象

如果要比较 java 中字符串的 2 个字符,要访问这些字符,您必须使用 String function charAt(index) 对于上述问题的解决方案是这样的:

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

对于String等引用数据类型, ==比较两个对象的引用地址,即memory地址是否相同。 如果memory地址相同,自然是相同的object。 什么是相同对象之间的比较。

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


/**
* 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;

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

当然,如果你知道自己在做什么,你必须利用==的这个特性,自然是没有问题的。 在其他时候,使用equals()方法。

在 Java 中,字符串有其专用的字符串类型,它不是数组,因此您无法使用方括号访问其字符。 相反,您应该使用 String 方法来比较 2 个字符串或访问它们的字符。 对于字符串比较,使用 equals():

aString.equals(anotherString)

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

"Hello!".charAt​(1); // returns 'e'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM