comlen function in Java
in c or c++
the functioncomlen
is defined such
int comlen(char *p,char *q){
int i=0;
while *p && (*p++==*q++)
i++;
return i;
}
Is this code equivalent of this function?
开发者_如何学编程int comlen(String s,String m){
int i=0;
while (i<s.length() && s.charAt(i)==m.charAt(i)){
i++;
}
return i;
}
Would I be correct in assuming this function returns how many characters are identical starting at the beginning of the string?
You may want to check out Apache Commons Lang StringUtils
and its indexOfDifference
method.
Otherwise, this function should work (but I haven't tested it):
public int comlen(CharSequence s, CharSequence m) {
int end = s.length() > m.length() ? m.length() : s.length();
int i = 0;
while (i < end && s.charAt(i) == m.charAt(i)) {
i++;
}
return i;
}
Note that CharSequence is an interface that is used by String
, StringBuffer
, and StringBuilder
rather than just String
.
The two are nearly equivalent. However, since C++ does not do bounds checking for you and Java does, you need to check for the end of either string in the Java example, rather than just checking for the end of s.
No, they are not equivalent. The Java function will fail with an exception if the first parameter is shorter than the second. The C/C++ function gives the correct result even in that case.
精彩评论