您的位置:首页 > 其它

编写函数void count(char a[],char w[][10],int n,int b[])。

2017-08-06 18:58 621 查看
 编写函数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
[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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐