Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract string value from a string

Tags:

c

gcc 4.4.3 c89

I have the following string

sip:[email protected]

How can I extract just the number? I just want the number.

12387654345443222118765

Many thanks for any advice,

like image 499
ant2009 Avatar asked Aug 16 '26 04:08

ant2009


2 Answers

There are lots of ways to do it, if the string is well-formatted you could use strchr() to search for the : and use strchr() again to search for the @ and take everything in between.

Here is another method that looks for a continuous sequence of digits:

char *start = sipStr + strcspn(sipStr, "0123456789");
int len = strspn(start, "0123456789");

char *copy = malloc(len + 1);

memcpy(copy, start, len);
copy[len] = '\0'; //add null terminator

...
//don't forget to
free(copy);
like image 141
Artelius Avatar answered Aug 18 '26 19:08

Artelius


It sounds like you want it as a numeric type, which is going to be difficult (it's too large to fit in an int or a long). In theory you could just do:

const char* original = "sip:[email protected]";
long num = strtoul(original + 4, NULL, 10);

but it will overflow and strtoul will return -1. If you want it as a string and you know it's always going to be that exact length, you can just pull out the substring with strcpy/strncpy:

const char* original = "sip:[email protected]";
char num[24];
strncpy(num, original + 4, 23);
num[23] = 0;

If you don't know it's going to be 23 characters long every time, you'll need to find the @ sign in the original string first:

unsigned int num_length = strchr(original, '@') - (original + 4);
char* num = malloc(num_length + 1);
strncpy(num, original + 4, num_length);
num[num_length] = 0;
like image 44
Michael Mrozek Avatar answered Aug 18 '26 18:08

Michael Mrozek