comlen function in Java

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;
}
2

3 Answers

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.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like