简体   繁体   English

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

[英]Reduce String.charAt to one loop during String comparison

I need to compare two strings that are of varying length and as such I have written two conditional loops depending on which String is longest: 我需要比较两个不同长度的字符串,因此我写了两个条件循环,具体取决于哪个字符串最长:

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
         }  

}

I decided to re-write it as so: 我决定重写它:

boolean compare(String first, String second)  
    {  
       int lengthDifference = first.length() - second.length(); 
       for(int i = 0; i < first.length() + lengthDifference;i++)  
         //charAt code here    
    }

I want to avoid having 1) two loops and 2) out of bounds exceptions. 我想避免1)两个循环和2)超出范围的异常。 My question is does the above implementation have a corner case that I am missing or should this work for all possible inputs. 我的问题是上面的实现是否有一个我错过的极端情况,或者这应该适用于所有可能的输入。

Your revised version will break if the second string is longer. 如果第二个字符串更长,您的修订版本将会中断。

Use: 采用:

int combinedLength = Math.min(first.length(), second.length());

then your condition only needs to be: 那你的病情只需要:

i < combinedLength

Simply use the lowest one: 只需使用最低的一个:

//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