主要代码有了,就是不知道怎么能实现要求,一行输入。
#include
#include
#include
#define N 10
void count(char a[],char w[][10],int n,int b[])
{
int count = 0;
int count1 = 0;
int i = 0;
int j = 0;
char *ptr = a;
for(j = 0;j < n;j++)
{
while(*ptr)
{
if(strncmp(ptr,w[j],strlen(w[j])) == 0)
{
count++;
ptr += strlen(w[j]);
}
else
{
ptr++;
}
}
b[count1] = count;
count1++;
count = 0;
ptr = ptr-strlen(a);
}
for(i = 0;i < count1;i++)
{
printf("%s:%d ",w[i],b[i]);
}
}
int main()
{
char a[100] = {0};
char w[10][10] = {0};
int b[N] = {0}; //存放统计结果
int n = 0; //统计单词的个数
int i = 0;
count(a,w,n,b);
return 0;
}
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void count(char a[], char w[][10], int n, int b[]) {
int i, j, k;
for (i = 0; i < n; i++) {
b[i] = 0;
}
i = 0;
while (a[i] != '\0') {
while (!isalpha(a[i]) && a[i] != '\0') {
i++;
}
j = 0;
while (isalpha(a[i]) && a[i] != '\0') {
w[j][k] = a[i];
i++;
j++;
}
for (k = 0; k < n; k++) {
if (strcmp(w[j], w[k]) == 0) {
b[k]++;
}
}
}
}
int main() {
char a[100];
char w[100][10];
int b[100];
int n, i;
printf("Enter a string: ");
gets(a);
printf("Enter the number of words: ");
scanf("%d", &n);
count(a, w, n, b);
printf("Word counts:\n");
for (i = 0; i < n; i++) {
printf("%s: %d\n", w[i], b[i]);
}
return 0;
}
C语言用scanf
char str[2000]={0};
scanf("%s",str);
char a[100];
scanf("%s",a);