字符串中数字求和
给定一个字符串,计算字符串中数值的个数并求和。其中还包含了负号-,若紧跟负号的是一个数值,则表示这是一个负数,若后面跟着的不是数字,则不表示什么
输入:一个字符串 输出:数值个数 数值和 例子
输入:312ab-2-- -9--a
输出:3 301
#include<stdio.h>
#include <stdlib.h>
#include<math.h>
#include<string.h>
int strToint(char* str)
{
int sign,sum,k,i,len,num;
sign = 1;
sum = i = 0;
len = strlen(str);
if(str[i]=='-')
{
sign = -sign;
i++;
}
if(str[i]=='+')
{
i++;
}
num = 0;
for(;i<len;i++)
{
//sum += sum*int(pow(10,num))+(str[i]-'0');
sum = sum*10+(str[i]-'0');
//num++;
}
return sum*sign;
}
int main()
{
int i,len,j;
char str[1000001],tep[1000001],c;
double b = 0.9999;
int sum = 0;
gets(str);
len = strlen(str);
//i = atoi(str);
//b = atof(str);
//printf("%lf\n",b);
//sprintf(str,"%.3lf hello",b);
//puts(str);
j =0;
for(i=0;i<len;i++)
{
c = str[i];
if(str[i]=='-')
{
if(j>0)
{
sum+=strToint(tep);//atoi(tep);
memset(tep, 0, sizeof(tep));
}
j=0;
if(str[i+1]>='0'&&str[i+1]<='9')
{
tep[0]='-';
j++;
}
}
else
{
if(str[i]>='0'&&str[i]<='9')
{
tep[j] = str[i];
j++;
//if(i==len-1)
}
else
{
tep[j]='\0';
if(j>0)
{
sum+=strToint(tep);//atoi(tep);
memset(tep, 0, sizeof(tep));
j=0;
}
}
}
}
if(j>0)
{
sum+=strToint(tep);
}
printf("%d\n",sum);
return 0;
//312df-2ff--9
#include <stdlib.h>
#include<math.h>
#include<string.h>
int strToint(char* str)
{
int sign,sum,k,i,len,num;
sign = 1;
sum = i = 0;
len = strlen(str);
if(str[i]=='-')
{
sign = -sign;
i++;
}
if(str[i]=='+')
{
i++;
}
num = 0;
for(;i<len;i++)
{
//sum += sum*int(pow(10,num))+(str[i]-'0');
sum = sum*10+(str[i]-'0');
//num++;
}
return sum*sign;
}
int main()
{
int i,len,j;
char str[1000001],tep[1000001],c;
double b = 0.9999;
int sum = 0;
gets(str);
len = strlen(str);
//i = atoi(str);
//b = atof(str);
//printf("%lf\n",b);
//sprintf(str,"%.3lf hello",b);
//puts(str);
j =0;
for(i=0;i<len;i++)
{
c = str[i];
if(str[i]=='-')
{
if(j>0)
{
sum+=strToint(tep);//atoi(tep);
memset(tep, 0, sizeof(tep));
}
j=0;
if(str[i+1]>='0'&&str[i+1]<='9')
{
tep[0]='-';
j++;
}
}
else
{
if(str[i]>='0'&&str[i]<='9')
{
tep[j] = str[i];
j++;
//if(i==len-1)
}
else
{
tep[j]='\0';
if(j>0)
{
sum+=strToint(tep);//atoi(tep);
memset(tep, 0, sizeof(tep));
j=0;
}
}
}
}
if(j>0)
{
sum+=strToint(tep);
}
printf("%d\n",sum);
return 0;
//312df-2ff--9
}