Compare Strings as if they were numbers

纵然是瞬间 提交于 2019-12-05 13:28:48

Since the only way to do this is to keep a set value for each word, you'd be using arrays, or some other form of data storage.

Here is an example where you just keep the words, and their corresponding values in two arrays (note, they must be in the same order, so the first word corresponds with the first number, etc).

public static String[] words = {"cat","dog","banana"};
public static int[] value = {3,4,5};
public static void main(String[] args){
    if(valOf("Cat") > valOf("Dog")){
        System.out.print("Cat is greater than Dog");
    }
    else{
        System.out.print("Cat is not greater than Dog");
    }
}
public static int valOf(String str){
    for(int x=0;x<words.length;x++){
        if(str.equalsIgnoreCase(words[x])){
            return value[x];
        }
    }
    return -1;
}

You can't use operators (e.g. "Cat" < "Dog") as you suggest. As @larsmans says that would require operator overloading which Java doesn't provide. However, you can still compare strings using "Cat".compareTo("Dog") which returns 0 if the strings are equal, a number greater than 0 if "Cat" is lexicographically less than "Dog", or a negative number otherwise.

See this page

Just implement the Comparator interface and implement the comparison any way you like.

Here is the Javadoc

Fred Foo

You can't. This would require operator overloading, which Java won't let you.

Nope, doesn't exist. You have to use compareTo().

You can use the compareTo method in String

You need to use some method as below :

int compare(String s1, String s2);   // write code to do comparison.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!