# Given input as a string, return an integer as the sum of all numbers found in the string?

175 views

Given input as a string, return an integer as the sum of all numbers found in the string

Input: xyzonexyztwothreeeabrminusseven
Output : 1 + 23 + (-7) = 17

posted Jun 7, 2017

do you mean sum of ascii representation of chars
I think question is very clear here its not about the ascii representation rather the word present in the string, look at the sample input and output provided in the question.

+1 vote

Not the exact solution but you can refer this program to get your job done.

``````#include<stdio.h>
#include<string.h>
void getSubString(char *ptr,int i);
int getSum(char *ptr,char *temp,int i);
main()
{
char str[100];
printf("Enter a string : ");
scanf("%[^\n]",str);
int i=0,sum=0;
while(str[i])
{
str[i]=toupper(str[i]);
i++;
}
char subStr[10];

for(i=0;i<10;i++)
{
getSubString(subStr,i);
sum=sum+getSum(str,subStr,i);
}
printf("SUM = %d\n",sum);
}
int getSum(char *ptr,char *subPtr,int num)
{
char *temp=NULL;
int sum=0;
while(*ptr)
{
temp=strstr(ptr,subPtr);
if(temp==NULL)
return sum;
sum=sum+num;
ptr=temp;
ptr++;
}
return sum;
}
void getSubString(char *ptr,int i)
{
switch(i)
{
case 0:
strcpy(ptr,"ZERO");
break;
case 1:
strcpy(ptr,"ONE");
break;
case 2:
strcpy(ptr,"TWO");
break;
case 3:
strcpy(ptr,"THREE");
break;
case 4:
strcpy(ptr,"FOUR");
break;
case 5:
strcpy(ptr,"FIVE");
break;
case 6:
strcpy(ptr,"SIX");
break;
case 7:
strcpy(ptr,"SEVEN");
break;
case 8:
strcpy(ptr,"EIGHT");
break;
case 9:
strcpy(ptr,"NINE");
break;
default:
break;
}
}
``````
Similar Questions

Given a dictionary of strings and another string find out if the string is an exact match to some words in the dictionary or varies at most in only one place of some word of the dictionary?

Given a string, add some characters to the from of it so that it becomes a palindrome.
e.g.
1) If input is "abc" then "bcabc" should be returned.
2) input -> "ab" output -> "bab"
3) input -> "a" output -> "a"

Given an unordered array A of size n and integer x. What is the best complexity to find two elements in A whose sum is x?
Share the algo, its complexity and if possible C code.