This is a piece of code I’ve written for a homework. It seems to work but I wonder if I missed something.
The task was to implement a function (here: Countwords) which counts all words in a char *. No library functions should be used.
namespace {
bool IsPrintable(char c) {
return c >= '!' && c <= '~';
}
void SkipPrintable(const char *&s) {
do {
s++;
} while (IsPrintable(*s));
}
bool IsWhiteSpace(char c) {
return c == ' ' || c == '\t' || c == '\n';
}
void SkipWhitespace(const char *&s) {
while (IsWhiteSpace(*s)) {
s++;
}
}
} // namespace
int CountWords(const char *s) {
int count = 0;
while (*s != '\0') {
SkipWhitespace(s);
if (IsPrintable(*s)) {
count++;
SkipPrintable(s);
}
}
return count;
}
You solve this in linear complexity. One cannot do the same in less complexity. So you cannot significantly improve your algorithm.