繁体   English   中英

在String比较期间将String.charAt减少到一个循环

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM