[英]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.
对于一个小项目,我尝试不使用API字符串就直接编写自己的compareToIgnoreCase()方法。 In the program, the user enters a string and the class definition converts the string to a char array.
在程序中,用户输入一个字符串,并且类定义将字符串转换为char数组。 The user will enter another string and it will compare it to the first string entered.
用户将输入另一个字符串,并将其与输入的第一个字符串进行比较。 Here is my
compareTo()
method I wrote. 这是我编写的
compareTo()
方法。 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: 假设您可以使用
java.lang.Character
很好,一种忽略大小写的可能解决方案是在比较每个字符之前将其转换为小写:
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. 因此,基本上,我们将以小写形式转换字符数组,以便您可以轻松地在两个char数组之间进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.