I'm trying to find the shortest word in a given C string, but somehow it fails if there is only one word or if it's the last word.
I tried start at the null character and count backwards until I hit " "
and than count the steps I took but it did not work properly.
Also is there a better or faster way to iterate through a string while finding the shortest or longest word?
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
ssize_t find_short(const char *s) {
int min = 100;
int count = 0;
for (int i = 0 ; i < strlen(s); i++) {
if (s[i] != ' ') {
count++;
} else {
if (count < min) {
min = count;
}
count = 0;
}
if (s[i] == '\0') {
count = 0;
while (s[i] != ' ') {
--i;
count++;
if (s[i] == ' ' && count < min) {
min = count;
}
}
}
}
return min;
}