1753481 Members
4417 Online
108794 Solutions
New Discussion юеВ

C/C++ program

 
SOLVED
Go to solution
RobertClark
Occasional Contributor

C/C++ program

How can i find the occurence of digit in string
it should be in C/C++.
Assume this string as input,

string12.def
string41.abc
string19.cef

function should return me number
for example in string12 should return me int 12 for example 2 it should return me 41.

4 REPLIES 4
Peter Godron
Honored Contributor

Re: C/C++ program

Robert,
you can loop through the string and isdigit test each char. If it is a digit, copy it to a second string and then atoi this second string to an integer.

Also see:
http://forums1.itrc.hp.com/service/forums/helptips.do?#33
Peter Godron
Honored Contributor
Solution

Re: C/C++ program

Robert,
my C is pretty lousy, so I am sure you can do better.

#include

int main( int argc, char *argv[] )
{
int a;
int c=0;
char IDATA[100];
char ODATA[100];
/* Get input data */
strcpy(IDATA,argv[1]);
/* Read through the string */
for (a=0;a<=(strlen(IDATA)-1);a++)
{
/* If it is a digit append to the Output */
if (isdigit(IDATA[a]))
{
ODATA[c]=IDATA[a];
c++;
}
}
printf("%s\n",IDATA);
printf("%d\n",atoi(ODATA));
}
A. Clay Stephenson
Acclaimed Contributor

Re: C/C++ program

Actually sscanf is perfectly capable of doing this task all on its own.

#include
#include

int parse_integer(char *instring)
{
int out = 0,i = 0;
char s[3][512];

while (i < 3) /* null the strings */
{
s[i] = '\0';
++i;
}
(void) sscanf(instring,
"%[^0-9]%[0-9]%[^0-9]",
s[0],s[1],s[2]);
if (strlen(s[2]) != 0) out = atoi(s[2]);
return(out);
} /* parse_integer */

Man scanf for details.

If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: C/C++ program

Oops, I'm stupid.

if (strlen(s[2]) != 0) out = atoi(s[2]);

SHOULD BE:
if (strlen(s[1]) != 0) out = atoi(s[1]);
If it ain't broke, I can fix that.