原文:
我出的一道测试题,在此公布,没有版权,随便转抄:有一个字符串,里面包含一些数字,写一个函数,把这些数字加起来。比如“我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(®ex,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(®ex,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(®ex);
return 1;
}