Ryan Corkwell
Ryan Corkwell

Reputation: 11

Writing my own compareToIgnoreCase method

So I've looked around for a similar question for a day or two now and it seems like this is a new topic. For a little project, I'm trying to hand write my own compareToIgnoreCase() method without using the API for strings. In the program, the user enters a string and the class definition converts the string to a char array. The user will enter another string and it will compare it to the first string entered. Here is my compareTo() method I wrote. My question is, how would I edit this to ignore the case while comparing.

public int compareTo(MyString anotherMyString) {
    if(anotherMyString.sequence[i] > 0) {
        return 1;
    } else if(anotherMyString.sequence[i] == 0) {
        return 0;
    } else {
        return -1;
    }
}

Upvotes: 0

Views: 220

Answers (2)

frozen
frozen

Reputation: 2154

Assuming you're ok with using java.lang.Character, one possible solution to ignore case is to convert each char to lowercase before comparing them:

char1 = Character.toLowerCase(char1);
char2 = Character.toLowerCase(char2);

// compare char1, char2

Upvotes: 2

Vishal Shevale
Vishal Shevale

Reputation: 64

You can use below logic,code

char charInput[] = new char[]{'A', 'B', 'C'};
for (int i = 0; i < charInput.length; i++) 
{
    char a = charInput[i];
    //This will make your char to lower case if it is in uppercase.
    if(a >=65 && a<= 90)
        a+=32;
    charInput[i] = a;
}

So, Basically we will convert array of character in lower case so that you can easily make comparison between both char arrays.

Upvotes: 0

Related Questions