偶尔看到刘涛涛的一个题,试着做了下(C语言实现)

原文:

我出的一道测试题,在此公布,没有版权,随便转抄:有一个字符串,里面包含一些数字,写一个函数,把这些数字加起来。比如“我30你40他50”结果就是120

代码(支持浮点型,但是觉得有点太长了,希望批评指正):

#include <stdio.h> //io
#include <iostream>
#include <sys/types.h>
#include <cstring>
#include <malloc.h>
#include <stdlib.h> //atoi
#include <regex.h> //regcomp
using namespace std;

int main(int argc,char** argv)
{
	char regexSrc[100] = "aaa10,23.5我是谁33bs1.3dsfa60";
	char pattern[20] = "[0-9]+\\.?[0-9]*";//\\. equals \.
	
	/*typedef struct
	{
	   regoff_t rm_so;//the start offset of the next largest substring match within the string.eg.offset of '1' within "aaa10," 
	   regoff_t rm_eo;//the end offset of the match, which is the offset of the first character after the matching text.eg.offset of ',' within "aaa10,"
	} regmatch_t;*/
	regmatch_t pmatch[1];
	const size_t nmatch = 1;
	regex_t regex;
	double sum = 0.0;
	int offset = 0;
	
	//regex compile
	//REG_NOSUB:run very fast,butregexec not contains the next largest substring
	regcomp(&regex,pattern,REG_EXTENDED);
	while(true)
	{
		//REG_NOTBAL:The first character of the string pointed to by string is not the beginning of the line
		//REG_NEWLINE:don't ignore '\n'
		int status = regexec(&regex,regexSrc+offset,nmatch,pmatch,REG_NOTBOL);
		
		//judge status from regexec
		if(status==REG_NOMATCH)
		{
			printf("the sum of numbers within string:%f\r\n",sum);
			break;
		}
		else if(status == 0)
		{		
			int len = pmatch[0].rm_eo-pmatch[0].rm_so;
			char* pValue = (char*)malloc((len+1)*sizeof(char));
			if(pValue==NULL)
			{
				printf("STATUS_INSUFFICIENT_RESOURCES!!\r\n");
				break;
			}
			else
			{
				memset(pValue,0L,len+1);
				memcpy(pValue,regexSrc+offset+pmatch[0].rm_so,len);
				sum += atof(pValue);
				printf("value:%s\r\n",pValue);
				
				free(pValue);
				pValue = 0;
				offset += pmatch[0].rm_eo;
			}
		}
		else
		{
			printf("regexec ret:%d\r\n",status);
			break;
		}
	}
	
	regfree(&regex);
	return 1;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值