I am trying to write a function that accepts a string and a word, and output the number of times it appears inside the string.
My bid:
int CountWord(char *s, char *word) {
char first = word[0];
int i, j, count = 0;
while (s[i] != '\0') {
if (s[i] == first)
for (j = 1; (s[i+j] == word[j]) && (word[j] != '\0') && (s[i+j] != '\0'); ++j) {
if (word[j] == '\0')
++count;
}
}
return count;
}
The problem: It doesn't work on "code-blocks".
Thanks in advance for your appreciated help.
There are multiple problems in your code:
i
i
(word[j] != '\\0')
in the for
loop prevents the counting code from ever executing. word
is the empty string. int
might not have the required range for very long strings on some architectures. Here is a corrected version:
size_t CountWord(const char *s, const char *word) {
char first = word[0];
size_t i, j, count = 0;
if (first == '\0')
return strlen(s) + 1;
for (i = 0; s[i] != '\0'; i++) {
if (s[i] == first) {
for (j = 1; word[j] != '\0' && s[i + j] == word[j]; j++)
continue;
if (word[j] == '\0')
count++;
}
}
return count;
}
Note that this implementation will return 2
for CountWord("aaa", "aa")
which may or may not be the expected result. The specification must be precise and tell whether to count overlapping occurrences of word
or just non overlapping matches.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.