c语言统计字符串中指定的单词个数

比如字符串:asgeage ghelloae gegahellosd hell oage hello
提取的单词为:hello
输出结果为:3
最好有代码注释 在线等答案
提供算法也行

给你个类似的。。。你小改下,就应该可以了。希望对你有帮助

/*编写一个函数,该函数可以统计一个长度为2的字符串在另一个字符串中出现的次数。

例如,假定输入的字符串为:asd asasdfg asd as zx67 asd mklo,

子字符串为:as,则应输出6。

[程序分析]

由于小串中只有2个字符所以可用str[i]==sbustr[0]&&str[i+1]==substr[1]来判断小串是否与长串当前位置(str[i])相同(即出现一次)。

因而只要让长串当前位置逐一向后移即可(用for()循环来完成)

 */

//[源程序]

#include "stdio.h"

#include "string.h"

#include "conio.h"

int fun(char *str,char *substr)

{ int i,n=0,s=strlen(str);

for(i=0;i<s;i++)

if((str[i]==substr[0])&&(str[i+1]==substr[1]))

n++;

return n;

}

main()

{

char str[81],substr[3];

int n;

printf("输入的字符串:");

gets(str);

printf("子字符串:");

gets(substr);

puts (str);

puts(substr);

n=fun(str,substr);

printf("n=%d\n",n)

}

/*******************************************************************************************************/

按你的意思我改了下调用函数里的

int fun(char *str,char *substr)

{

int i,j,n=0,s=strlen(str),m=strlen(substr),pan=1;

printf("%d\n",m);

for(i=0;i<s;i++)

{ pan=1;

for(j=0;j<m;j++)

if((str[i+j]!=substr[j]))//这是进行比较,不是跳出

  {pan=0;

  break;}

  if(pan)

n++;

 }

return n;

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-05-10
#include <stdio.h>
#include <string.h>
int search_string(char *target,char *search)
//target可以为"asgeage ghelloae gegahellosd hell oage hello"
//search可以为"hello"
{
bool judge = true;
int n = 0;
for(int i = 0; i < strlen(target); i++)
{
judge = true;
for(int j = 0; j < strlen(search); j++)
if(target[i+j] != search[j])
{
judge = false;
break;
}
if(judge)
n++;
}
return n;
}
void main(void)
{
char target[400] = {0},search [400] = {0};//
printf("输入:\n");
gets(target);
printf("输入要查找的字符串\n");
scanf("%s",search);
printf("出现的次数为:%d\n",search_string(target,search));
}

不懂再问哈本回答被网友采纳

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网