2017-08-12 46 views
0

This is my previous question子不在此行<code>lastDot</code>越來越問題工作

在我上面的問題的回答return id.substring(0, lastDot - 1);

如果我有ID 1.1在上面的行lastDot值是1子字符串變得""

我該如何避免這個問題。

private String getParentId(String id) { 
    int lastDot = id.lastIndexOf("."); 
    if (lastDot == -1) { 
     return null; 
    } 
    return id.substring(0, lastDot - 1); 
} 
+1

閱讀子字符串的文檔。如果你注意,你會看到你的誤解。不要減去。閱讀文檔和使用代碼進行實驗要比在SO上提出要快。自問你已經16分鐘了。這在調試器中可以很容易地修復一兩分鐘。每個問題都不適合在這裏詢問。 – duffymo

+0

在你的例子中, 子字符串似乎是錯誤的方法。 考慮在'。'上使用拆分和拆分。 – DwB

回答

4

檢查Java文檔:https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

第二個參數是從第一個參數開始的字符串的長度,所以如果你總是與指數0開始,你並不需要減去1

return id.substring(0, lastDot); 

一個更普遍的做法是始終減去第一個參數

int offset = 0; 
return id.substring(offset, lastDot-offset); 
1
return id.substring(0, lastDot); 

是你的意思。但想想你的身份證是1.2.3這種情況下返回的情況是什麼? 1.221。目前您的功能將返回1.2,這可能是正確的 - 但這取決於您的需求。