比较字符串,就好像它们是数字一样 [英] Compare Strings as if they were numbers

查看:58
本文介绍了比较字符串,就好像它们是数字一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将字符串当作数字进行比较.例如,有什么办法可以使"Cat" > "Dog"

I was wondering if it is possible to compare strings as if they were numbers. For instance is there any way you could make it so that "Cat" > "Dog"

推荐答案

由于这样做的唯一方法是为每个单词保留一个设置值,因此您将使用数组或某种其他形式的数据存储.

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

这篇关于比较字符串,就好像它们是数字一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆