您的位置:首页 > 其它

百度笔试题---某文本段,包含数字,空格,逗号,句号。设计统计句子量函数

2012-05-04 23:51 351 查看

/*
* file name : calculate_sentence.c
* function  : calculate the number of sentence
* date      : 2012-5-4
* author    : enyblock
*/

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

int calculate_sentence(char *str);

int main (void)
{

char *text = ".   a . psdf ,dsf . dfdf,dfhjk dadf,df. a . asdf ,asdsfasf.  .";

int  num =  calculate_sentence(text);

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

return EXIT_SUCCESS;
}

/*the fucntion of calculate sentence*/
int calculate_sentence(char *str)
{
char *temp = str;		/*remember the initial location*/
int  num  = 0;
char *temp2 = NULL;

while (*str != '\0'){   /*find the last character*/

if (*str == '.'){	/*find the '.'*/

temp2 = str;	/*remember the find location*/

while (((str-1) != (temp-1)) && ((*(str-1)) != '.')){	/*not reach the initail location and not equal the character '.' */

if (isalpha(*(str-1))){								/*juege the alpha*/
num++;
break;
}

str--;												/*search the forward character*/

}

str = temp2;											/*restore the str*/
}

str++;
}

return num;
}


1.思路

首先查找句号,然后往前搜索,如果遇到字母,则计数器加1

2.实现

首先,判断字符串是否到结尾,一直查找句号,待查找到句号,然后往前搜索(此时需要记住当前指针,因为往前搜索,指针要移动,为了以后恢复而用)

然后,循环往前搜索,跳出循环的条件为:前一个字符为句号 或者 前一个字符的指针移动超过的初始化指针。进入循环后,判断前一个字符是否为字母,如果是的话,计数器加一

最后,注意恢复指针,因为向前搜索后,指针前移了,为了计算下一个句子,需要将指针恢复。

3.可以处理情况

首字母为句号

两个句号之间没有字母

句号前有字母

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