Sum the numbers in a string

Source: Internet
Author: User

Given a string, computes the number of values in the string and sums them. It also contains the minus sign-if the minus sign is a numeric value, then it is a negative number, if followed by not numbers, it does not mean what input: A string output: Numeric values and example input: 312ab-2---9--a

Output: 3 301

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
intStrtoint (Char* str)
{
intSign,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*Ten+ (str[i]-'0');
//num++;
}

returnSum*sign;
}
intMain ()
{
intI,len,j;
Charstr[1000001],tep[1000001],c;
Doubleb =0.9999;
intsum =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]=' /';
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);
return0;
//312df-2ff--9

}

Sum the numbers in a string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.