Compare different length char arrays in c++ without string library
I have 2 char arrays, one with length 50, other whose length varies from 1...50. I need to compare these.
The problem is, that the array containing 50 chars, usually contains less chars, but when comparing, it also takes them into account. So if I have 2 array, whose value is U2
, length开发者_StackOverflow社区 of first will be 50, the second - 2.
So, how do I check this, without using the standard string library? I must not use the string library, that is a prerequisite.
If you aren’t allowed to use the standard library functionality then your first task is to re-program the required functionality. In your example, this would be strcmp
.
Programming this function isn’t difficult – searching online should find you several possible implementations.
Roughly:
- Start walking through both strings in a loop until encountering a null char in either string.
- If both terminate in a null char at the same time, they are equal; otherwise the longer string is greater.
- Inside the loop, compare each individual character.
- If the characters are equal, continue;
- Otherwise, return.
If the strings have different sizes, I think you are better with strncmp()
:
int strncmp(const char *s1, const char *s2, size_t n);
From the man pages:
It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.
There's a custom implementation here to get you started.
精彩评论