Avatar of superwick
superwick
 asked on

stripping non numeric values from char array

say i have an array of chars

char temp[];
strcpy(temp,"$100,000.00");

now i want to just take out all the non numeric values such as $ , and .
the string in temp is not always going to be $100,000.00 , it could be $1,000.00 or $1,000,000.00.

I tried doing something like

if temp[i]>47 && temp[i]<58 {
 then do something
}

but it seems to not filter out non numerical values. Do i just have the ascii values wrong or should i be taking a different approach to filtering out the non numerical values?
C

Avatar of undefined
Last Comment
evilrix

8/22/2022 - Mon
evilrix

ASKER CERTIFIED SOLUTION
evilrix

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
ozo

error: array size missing in 'temp'

but you can
  char temp[100];
  strcpy(temp,"$100,000.00");
  for(i=j=0;temp[j]=temp[i];i++){ if( temp[i]>47 && temp[i]<58 ){ j++; } }

peetm

Or strtok it ...

    char before[100];
    char after [100] = "";
   
    const char * delim = " $,.-";
   
    char * pch;
   
    strcpy(before,"$100,000.00");

    pch = strtok (before, delim);
   
    while(pch != NULL)
    {
        strcat(after, pch);

        pch = strtok (NULL, delim);
    }
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
superwick

ASKER
that was so simple. wow.. haha. i didn't even think to look for that
Infinity08

Note that instead of 47 and 58, it's nicer to use '0' and '9' (using <= and >= instead of < and > of course).
evilrix

If you want to do it in-place by shuffling the bytes down should do it.

NB. I've not tested it thoroughly, I'll leave that as an exercise for you to do :)
#include <ctype.h>
#include <string.h>
 
void strip(char * p)
{
	char *p1 = p;
	char *p2 = p;
	size_t len = strlen(p);
 
	do
	{
		if(!isdigit(*p1))
		{
			while((p2 < &p[len]) && !isdigit(*p2)) { ++p2; };
			*p1 = *p2;
			*p2 = 0;
		}
	}
	while(++p1 < &p[len]);
}
 
int main()
{
	char temp[] = "$100,000.00";
	strip(temp);
}

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.