簡體   English   中英

使用 charAt 比較 Java 中的兩個字符串

[英]Comparing two strings in Java using charAt

我必須使用 charAt() function 比較兩個字符串,如果字符串相同則返回 true,否則返回 false

public static boolean comparaStringhe(String word1, String word2) {
    if (word1.length() == word2.length()) {
        for (int i = 0; i < word1.length(); i++) {
            for (int j = 0; j < word2.length(); j++) {
                if (word1.charAt(i) == word2.charAt(j)) {
                    return true;
                } else {
                    return false;
                }
            }
        }
    }

    return false;
}

比較下列詞語:
1.測試-測試/
2.測試——測試/
3.測試-測試/
4. 測試-測試

實際 output:
1. 真的
2.假的
3. 真的
4. 真的

預期 output:
1. 真的
2.假的
3. 假的
4. 假的

您的代碼有兩個問題:
1.不需要雙循環,您將第一個單詞的每個字符與第二個單詞的每個字符進行比較,這是錯誤的。 一個循環就足夠了,比較word1.charAt(i) == word2.charAt(i)
2.如果第一個字符相等,則返回true,而不是繼續單詞的rest。 return true應該只在 for 循環結束之后出現

public static boolean comparaStringhe(String word1, String word2) {
        if (word1.length() == word2.length()) {
            for(int i=0; i<word1.length(); i++) {
                    if(word1.charAt(i) != word2.charAt(i)) {
                        return false;
                    }
            }
            return true;
        }

        return false;
   }

當兩個字符串的長度相同時,不需要兩個循環。 如果不匹配,也只需返回false 當循環結束時,這意味着沒有不匹配並且可以返回true

您在代碼有機會通過整個字符串返回 go 之前返回。

僅在遍歷整個字符串后才返回。

for(int i=0; i<word1.length(); i++) 
{
    for(int j=0; j<word2.length(); j++) 
    {
        if(word1.charAt(i) == word2.charAt(j)) 
        {
            // return true; the code is not able to traverse through the whole string.
        } 
        else 
        {
            return false;
        }
    }
    return true; // The code has now traversed the whole string and can now say that the strings match. Thus return true.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM