[英]Reduce String.charAt to one loop during String comparison
我需要比較兩個不同長度的字符串,因此我寫了兩個條件循環,具體取決於哪個字符串最長:
boolean compare(String first, String second)
{
boolean firstLongest = first.length() > second.length();
if(firstLongest)
{
for(int i = 0; i < first.length(); i++)
//charAt code here
}
else{
for(int i = 0; i < second.length();i++)
//charAt code here
}
}
我決定重寫它:
boolean compare(String first, String second)
{
int lengthDifference = first.length() - second.length();
for(int i = 0; i < first.length() + lengthDifference;i++)
//charAt code here
}
我想避免1)兩個循環和2)超出范圍的異常。 我的問題是上面的實現是否有一個我錯過的極端情況,或者這應該適用於所有可能的輸入。
如果第二個字符串更長,您的修訂版本將會中斷。
采用:
int combinedLength = Math.min(first.length(), second.length());
那你的病情只需要:
i < combinedLength
只需使用最低的一個:
//Maybe knowing what the length diff is interesting to achieve your goal:
int lenDiff = Math.abs(first.length() - second.length());
// The loop, taking the length of the shortest one as limit
for (int i = 0; i < Math.min(first.length(), second.length()); ++i)
{
// Char code here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.