C语言学习历程——编程练习3——01

来源:互联网 发布:数据库关系图 连线 编辑:程序博客网 时间:2024/05/16 10:00
 1. 编写函数void count(char a[],char w[][10],int n,int b[])。
  功能是:统计w指向的数组中的n个单词在a指向的字符串中各自出现的次数

  将非字母字符看作单词分割符,拧将统计结果依次保存在b指向的数组中


分析:在a字符串中寻找w中的每个单词,每次寻找的时候计数就可以了。


下面是代码实现:


/**********************************************************************
  编写函数void count(char a[],char w[][10],int n,int b[])。
  功能是:统计w指向的数组中的n个单词在a指向的字符串中各自出现的次数
  将非字母字符看作单词分割符,拧将统计结果依次保存在b指向的数组中
**********************************************************************/


#include <stdio.h>


#define N 4


int mystrlen(const char *str)
{
int length = 0;


while (*str++)
{
length++;
}


return length;
}


char* mystrstr(const char *str, const char *sub)  //在主串中查找子串,找到则返回首次出现的地址,否则返回NULL
{
int n = 0;


if (sub != NULL)
{
while (*str)
{
for (n = 0; (*(str + n) == *(sub + n)); n++)
{
if (*(sub + n + 1) == '\0')
{
return (char *)str;
}
}
str++;
}
return NULL;
}
else
{
return (char *)str;
}
}


void count(char a[], char w[][10], int n, int b[])
{
int i = 0;
int j = 0;
int count = 0;
char *p = a;


for (i = 0; i < n; i++)
{
p = mystrstr(p, w[i]); //在a中查找w[i]指向的单词


while (p != NULL)
{
count++;
p += mystrlen(w[i]);
p = mystrstr(p, w[i]); //找到之后计数器加一,并且将其出现次数放入b
}
b[j++] = count;
count = 0;
p = a;
}
}


void PrintArr(int *b, int n)  //打印数组b
{
int i = 0;


for (i = 0; i < n; i++)
{
printf ("%d  ", b[i]);
}
printf ("\n");
}


void PrintCarr(char w[][10], int n)  //打印数组w
{
int i = 0;


for (i = 0;i < n; i++)
{
printf ("%s ", w[i]);
}
printf ("\n");
}


int main()
{
char word[N][10] = {"hello", "world", "apple", "duck"}; //初始化w指向的单词
char a[100] = "lcchellowdkworldlcchellosdapplekducklikeduck"; //初始化a字符串
    int b[10] = {0};


printf ("The original string is : \n");
printf ("%s\n", a);

printf ("The original words are :\n");
count(a, word, N, b);
PrintCarr(word, N); //打印原始单词
printf ("The results are : \n");
PrintArr(b, N); //打印单词出现的次数


return 0;
}

0 0
原创粉丝点击