Java 检查字符串可变长度(带子字符串)

Java Check String Variable Length (with Substring)

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

 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,那么它将抛出错误。

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

由于您的所有检查都在测试字符串的开头,因此使用 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")) 

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