Skip to content

Hand-rolling a C string comparison

Question

Implement your own version of a function that compares two null-terminated C strings, returning negative, zero or positive as strcmp does.

Short answer

Advance both pointers while characters match and are non-null, then return the difference of the current characters. Cast to unsigned char before subtracting so characters above 127 compare correctly. This takes O(min⁡(m,n))O(\min(m,n)) time and O(1)O(1) space; handle the case where one string is a prefix of the other, which is caught by the terminating null.

Adapted from Joshi, Denson & Downes, Quant Job Interview Questions and Answers, Q7.11, p.226; question and answer rewritten by SelfMadeQuant.com.

See the hint and the full worked solution in the question bank (free account).

Open the worked solution

Lessons behind this question