[英]Java Check String Variable Length (with Substring)
我有一個String變量,每次運行時其長度都可以不同。 借助它,我檢查它的開頭,例如:
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”嗎? 謝謝。
由於所有檢查都在測試String的開頭,因此可以使用startsWith
而不是將substring
和equals
組合在一起,並且您不必擔心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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.