题目内容
(1)编写函数 void count ( char a [], char w []
[10], int n , int b [])。其功能是统计 w 指向的数组中的 n 个单词在 a 指向的字符串中各自出现的次数(将非字母字符看做单词分隔符),并将统计结果依次保存在 b 指向的
数组中。
(2)编写 main ()函数,从键盘输入字符串,将数据保存在数组中,调用 count ()函数做统计,并在屏幕上打印统计结果(每个单词及其出现次数)。
输入
输入一串字符串
输出
输出前两个单词出现的频率
输入样例
this is a book , that is an apple
输出样例
this :1 is :2
#include<stdio.h>
#include <string.h>
void count ( char a[], char w [][10], int n , int b [])
{
char s[100][10];
int m=0,i=0,j;
char *p = strtok(a," ");
while(p != NULL)
{
strcpy(s[m],p);
m++;
p = strtok(NULL," ");
}
//
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(strcmp(s[j],w[i]) == 0)
b[i]++;
}
}
}
int main()
{
char w[2][10];
char s[1000],r[1000];
int num[2] = {0};
int n=0,i=0;
gets(s);
while(s[i] != 0)
{
if(s[i] < 'a' || s[i] > 'z')
s[i] = ' ';
i++;
}
strcpy(r,s);
//
char *p = strtok(s," ");
while(p != NULL)
{
for(i=0;i<n;i++)
{
if(strcmp(w[i],p) == 0)
break;
}
if(i==n && n<2)
{
strcpy(w[n],p);
n++;
}
else
break;
p = strtok(NULL," ");
}
count(r,w,2,num);
for(i=0;i<2;i++)
printf("%s: %d ",w[i],num[i]);
//
return 0;
}
第一题:
#include <stdio.h>
#include <string.h>
void count(char a[], char w[][10], int n, int b[]) {
int i, j, k, len;
char temp[100];
// 将 a 指向的字符串拷贝到临时字符串 temp 中
strcpy(temp, a);
// 按照非字母字符分割 temp 字符串,并统计每个单词的出现次数
for (i = 0; i < n; i++) {
len = strlen(w[i]);
b[i] = 0;
for (j = 0; j < strlen(temp); j++) {
if (isalpha(temp[j])) {
k = 0;
while (k < len && isalpha(temp[j + k]) && temp[j + k] == w[i][k]) {
k++;
}
if (k == len) {
b[i]++;
j += len - 1;
}
}
}
}
}
第二:
#include <stdio.h>
#include <string.h>
void count(char *str)
{
char *p = strtok(str, " ");
int cnt[100] = {0};
char words[100][100];
int n = 0;
while (p) {
int i;
for (i = 0; i < n; i++)
if (strcmp(words[i], p) == 0)
break;
if (i == n)
strcpy(words[n++], p);
cnt[i]++;
p = strtok(NULL, " ");
}
for (int i = 0; i < 2; i++)
printf("%s :%d ", words[i], cnt[i]);
printf("\n");
}
int main()
{
char str[100];
scanf("%[^\n]", str);
count(str);
return 0;
}
通过空格将单词分开,放到数组中,然后循环,出现一次就+1 ,最后循环输出,其实不难的。自己按照这个思路写下,直接用别人的,自己就没有进步了不是 加油
#include<stdio.h>
#include <string.h>
void count ( char a[], char w [][10], int n , int b [])
{
char s[100][10];
int m=0,i=0,j;
char *p = strtok(a," ");
while(p != NULL)
{
strcpy(s[m],p);
m++;
p = strtok(NULL," ");
}
//
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(strcmp(s[j],w[i]) == 0)
b[i]++;
}
}
}
int main()
{
char w[2][10];
char s[1000],r[1000];
int num[2] = {0};
int n=0,i=0;
gets(s);
while(s[i] != 0)
{
if(s[i] < 'a' || s[i] > 'z')
s[i] = ' ';
i++;
}
strcpy(r,s);
//
char *p = strtok(s," ");
while(p != NULL)
{
for(i=0;i<n;i++)
{
if(strcmp(w[i],p) == 0)
break;
}
if(i==n && n<2)
{
strcpy(w[n],p);
n++;
}
else
break;
p = strtok(NULL," ");
}
count(r,w,2,num);
for(i=0;i<2;i++)
printf("%s: %d ",w[i],num[i]);
//
return 0;
}