tags:

views:

93

answers:

3

in c or c++
the function comlen 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;
}
A: 

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.

sth
@sth what will be correct form?
once you understand the problem, you'll understand how to fix it
leonbloy
we can use throws exception or enter constraints that both String are equal
+1  A: 

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.

VeeArr
+2  A: 

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.

R. Bemrose