【问题标题】:Java Check String Variable Length (with Substring)Java 检查字符串可变长度(带子字符串)
【发布时间】:2016-02-26 14:29:32
【问题描述】:

我有一个字符串变量,它每次运行时都可以有不同的长度。 有了它,我检查它的开头,例如:

 public void defineLocation(){
            if (newLocation.substring(0,2).equals("DO") || newLocation.substring(0,2).equals("30") || newLocation.substring(0,2).equals("21")) {
                locationInDc = "DOOR";
            } else if (newLocation.substring(0,2).equals("VT") || newLocation.substring(0,3).equals("MUF")) {
                locationInDc = "BLOUBLOU";
            } else if (newLocation.substring(0,3).equals("MAH")) {
                locationInDc = "BLOBLO";           
            } else if (newLocation.substring(0,7).equals("Zone 72") || newLocation.substring(0,7).equals("Zone 70")){
                locationInDc = "BLOFBLOF";
}

我知道这不是最有效的方法,而且它肯定会中断,如果我的变量不在前 3 次检查中的任何一个中,但字符数仍然少于 7,那么它将引发错误。

有没有更“正确”的方法来做到这一点?我应该先检查字符串包含多少个字符,然后将其指向正确的检查/“ifs”吗?谢谢。

【问题讨论】:

    标签: java string if-statement substring case


    【解决方案1】:

    由于您的所有检查都在测试字符串的开头,因此请使用 startsWith 而不是组合 substringequals,您不必担心 newLocation 太短。

    例如替换

    if (newLocation.substring(0,2).equals("DO") || newLocation.substring(0,2).equals("30") || newLocation.substring(0,2).equals("21")) 
    

    if (newLocation.startsWith ("DO") || newLocation.startsWith ("30") || newLocation.startsWith ("21")) 
    

    【讨论】:

    • 我不明白为什么有人反对它..!!! OP询问任何其他正确的方法来做到这一点,就是这样。
    • 好吧,即使是随机投票,Eran 也可能不会用完积分。
    • 开始于!我现在只是觉得很傻......非常感谢
    • 这样做的另一个好处是它避免了为每次比较创建新的字符串对象。
    【解决方案2】:

    使用 string.startWith 进行检查,并可能使用 Map 进行映射。

    Map<String,String> map = new HashMap<String,String>();
    map.put("DO", "DOOR");
    map.put("30", "DOOR");
    map.put("21", "DOOR");
    map.put("VT", "BLOUBLOU");
    map.put("MUF", "BLOUBLOU");
    map.put("MAH", "BLOBLO");
    map.put("Zone 72", "BLOFBLOF");
    map.put("Zone 70", "BLOFBLOF");
    
    for (Entry<String, String> entry : map.entrySet()) {
        if (newLocation.startsWith(entry.getKey())) {
            locationInDc = entry.getValue();
            break;
        }
    }
    

    【讨论】:

    • 地图的好主意,我会做的!谢谢@ArticLord
    猜你喜欢
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 2015-06-23
    • 2014-05-08
    • 1970-01-01
    • 2017-01-04
    • 2014-03-03
    • 1970-01-01
    相关资源
    最近更新 更多