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

 
 
/*
 * 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.可以处理情况

   首字母为句号

   两个句号之间没有字母

   句号前有字母

   ........

     

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值