C++统计单词数

2025-05-11 17:12:59
推荐回答(1个)
回答(1):

我的思路是,假设我们需要查询的字符串长度为 L ,从左到右依次扫描字符串,每扫描一个字符,就将这个字符以及后面的 L - 1个字符组成一个字符串与要查询的字符串进行对比。
但是很明显这个思路无法通过在 tototo 中查询 to 的情况,这个思路结果是 3,而正确的应该是 0 个。
其实我们只要判断一下 所有枚举 组成的字符串 的左右是不是都是空格,如果左右即不是空格也不是字符串边界,那该字符串不合法,continue就行了
···cpp
#include
#include
#include
#include
using namespace std;
char a[1000005], word[11], t[11];
int main() {
gets(word);
gets(a);
int ans = 0;
int pos = -1;
int lena = strlen(a);
int lenw = strlen(word);
for (int i=0; ia[i] = tolower(a[i]);
for (int i=0; iword[i] = tolower(word[i]);
for (int i=0; i+lenwif(!(i - 1 >= 0 && a[i - 1] == ' '
&& i + lenw < lena && a[i + lenw] == ' '))
continue;
int j;
for (j=0; jt[j] = a[i + j];
}
t[j] = '\0';
if (!strcmp(word, t)) {
ans++;
if(pos == -1)
pos = i;
}
}
if (ans) printf("%d %d\n", ans, pos);
else printf("-1\n");
return 0;
}