简体   繁体   English

使用 charAt 比较 Java 中的两个字符串

[英]Comparing two strings in Java using charAt

I must compare two strings using charAt() function and return true if the strings are the same or false if they arent我必须使用 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;
}

Comparing the following words:比较下列词语:
1. test - test / 1.测试-测试/
2. test - Test / 2.测试——测试/
3. test - tEst / 3.测试-测试/
4. tEsT- tesT 4. 测试-测试

Actual output:实际 output:
1. true 1. 真的
2. false 2.假的
3. true 3. 真的
4. true 4. 真的

Expected output:预期 output:
1. true 1. 真的
2. false 2.假的
3. false 3. 假的
4. false 4. 假的

Two problems with your code:您的代码有两个问题:
1. no need for double loop, you are comparing each char on the first word to each char on the second, that's wrong. 1.不需要双循环,您将第一个单词的每个字符与第二个单词的每个字符进行比较,这是错误的。 one loop is enough, and compare word1.charAt(i) == word2.charAt(i)一个循环就足够了,比较word1.charAt(i) == word2.charAt(i)
2. you are returning true if the first char is equal, and not continuing to the rest of the words. 2.如果第一个字符相等,则返回true,而不是继续单词的rest。 the return true should come only after the for loop as ended 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;
   }

There is no need for two loops when both Strings have the same length.当两个字符串的长度相同时,不需要两个循环。 Also just return false in case of a mismatch.如果不匹配,也只需返回false When the loop will finish it will mean that there were no mismatches and true can be returned.当循环结束时,这意味着没有不匹配并且可以返回true

You are returning before the code has a chance to go through the whole string.您在代码有机会通过整个字符串返回 go 之前返回。

return only after the whole string has been traversed.仅在遍历整个字符串后才返回。

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