简体   繁体   中英

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

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 /
2. test - Test /
3. test - tEst /
4. tEsT- tesT

Actual output:
1. true
2. false
3. true
4. true

Expected output:
1. true
2. false
3. false
4. false

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. one loop is enough, and compare 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. the return true should come only after the for loop as ended

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. When the loop will finish it will mean that there were no mismatches and true can be returned.

You are returning before the code has a chance to go through the whole string.

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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