Home > other >  How to use a charactercomparator to compare whether the characters in a string is the same or not?
How to use a charactercomparator to compare whether the characters in a string is the same or not?

Time:10-13

I have a method public boolean same which takes in a string w and I'm trying to use a character comparator d to check whether each character in the string is the same with each character in the reversed version of the string or not (a palindrome basically).

So what I've done is I've taken my string w and created another string S that returns the reversed version of the given string. After that, I have created a for loop and used my character comparator to compare each character in the two strings that I have, and the method would return True if all characters are the same and false otherwise.

Here is my code so far:

public boolean same(String w, CharacterComparator<Character> d) {
    String S = "";
    for (int i = w.length() - 1; i >= 0; i--) {
        S = S   w.charAt(i);
    }
    for (int x = 0; x < w.length()-1; x  ){
    if (d.equalChars(w.charAt(x), S.charAt(x))) {
        return true;}
    }
    return false;
} 

However, there seems to be a problem in my implementation of this as it's causing an error. Can anyone please explain what am I doing wrong and correct me?

Thank you.

CodePudding user response:

Please share the error message

But also I do notice the condition for x should be x < w.length()

CodePudding user response:

Your code has 2 problems

  1. is about reversing the string
  2. is about the return condition is not true, it return true even if there is only one characters match.

Try this code:

public boolean same(String w, CharacterComparator<Character> d) {
    String S = new StringBuilder(w).reverse().toString();

    for (int x = 0; x < w.length()-1; x  ) {
        if (!d.equalChars(w.charAt(x), S.charAt(x))) {
            return false;
        }
    }
    return true;
} 
  • Related