Java 在字符串比较期间将String.charAt减少为一个循环
我需要比较两个长度不同的字符串,因此根据哪个字符串最长,我编写了两个条件循环:Java 在字符串比较期间将String.charAt减少为一个循环,java,comparison,Java,Comparison,我需要比较两个长度不同的字符串,因此根据哪个字符串最长,我编写了两个条件循环: boolean compare(String first, String second) { boolean firstLongest = first.length() > second.length(); if(firstLongest) { for(int i = 0; i < first.length(); i++)
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个越界异常。我的问题是,上面的实现是否有一个我遗漏的角落案例,或者应该对所有可能的输入都起作用。如果第二个字符串更长,您的修订版本将中断 使用: 那么你的情况只需要是:
i < combinedLength
如果第二个字符串更长,则修改后的版本将中断 使用: 那么你的情况只需要是:
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
}
只需使用最低的一个:
//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
}
你在for循环中做什么?谢谢@Mechkov我正在做一个简单的charAt调用来寻找最短的字符串?@Mechkov是最短的字符串是的,最好的选择是使用下面答案中的数学API。当做你在for循环中做什么?谢谢@Mechkov我正在做一个简单的charAt调用来寻找最短的字符串?@Mechkov是最短的字符串是的,最好的选择是使用下面答案中的数学API。当做