#String comparisons in C
28 messages · Page 1 of 1 (latest)
I'm listening sensei rob
Let's start by just doing equality first
how would you implement this function
bool are_strings_equal(const char* s1, const char* s2) {
// ???
}
Since it outputs either 0 or negative or positive value (not just -1 or 1) its probably this:
I was going for a simpler one that just checks if they're equal but you can do the full strcmp as well
Well I was talking about most widely spread
let's go for the strcmp yea
In pseudo code it should compare if two char values are equal by subtracting one from another and only stoping if both strings end at the same length, we encounter first character + of the first string length or char1[I] - char2[I] != 0
But I think the second option still would fall under the third option BC ASCII math still work with /0 element
Wait no... O.o
int strcmp(const char *s1, const char *s2) {
size_t i = 0;
// Both strings need to have a character / can't be finished
while (s1[i] != '\0' && s2[i] != '\0') {
// If the characters are not the same, we subtract them with funny ascii magic to see which one is larger / smaller
if (s1[i] != s2[i]) {
return (unsigned char)s1[i] - (unsigned char)s2[i];
}
// Characters are the same -> move to the next character
i++;
}
// one or both ended
return (unsigned char)s1[i] - (unsigned char)s2[i];
}
something like this would work
I wonder not what would work but how it works, because I had an idea
your intuition was right
The actual implementation in the standard library is a little more complex for performance reasons (i.e. only comparing punters)
@dire mulch you wanna hear an idea
yes
?
Ok
So strcmp(word, wo) would perform slower then strcmp(word, do);
Because the method runs as many cycles as it has to do comparesons and stops when chars are not equal
So theoretically you could guess if you guessed a part of the string if it performs slower because you would do +1 cycle
Or strcmp(word, ww); is slower then strcmp(word,dw); to make clearer point
@dire mulch I know it's meaningless in grand scheme of things but theoretically it makes sense
yes
@dire mulch I am bothering you for nonsense