简体   繁体   中英

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

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

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.

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