I have a string "some random data/1000"
. Now, I want the number(1000
) alone without storing the first part anywhere. I should directly get the last part i.e the number. How to do this in C language?
Here '/'
is delimiter.
I have a string "some random data/1000"
. Now, I want the number(1000
) alone without storing the first part anywhere. I should directly get the last part i.e the number. How to do this in C language?
Here '/'
is delimiter.
If you're certain there's only one delimiter, I would simply use strrchr()
1 to find it. Then either directly convert the number to integer (using e.g. strtol()
) or allocate a new string and copy the trailing part of the first in there.
1 Please note that middle r
, it's searching backwards.
There are many ways to do it, but in your particular case
char string[] = "some random data/1000";
char *pointerTo1000 = strchr(string, '/');
if (pointerTo1000 != NULL)
{
pointerTo1000 += 1;
printf("%s\n", pointerTo1000);
}
should output 1000
, if you want to covert it to a number
char *endptr;
int value = strtol(pointerTo1000, &endptr, 10);
if (*endptr == '\0')
printf("converted successfuly: %d\n", value);
if some random data
contains a slash /
then strrchr
suggested by unwind is the right choice, and you can use it exactly as in my example.