0

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.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
mit23
  • 53
  • 6
  • There we are storing every part. Here I do not need to store the first part. My work is only with the numerical data at the end. Infact, the strings are large to store the first part. – mit23 Feb 19 '15 at 13:21

2 Answers2

2

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

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.

Community
  • 1
  • 1
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • avoid `printf("%s\n", pointerTo1000);` with `pointerTo1000` being NULL. There are systems (e.g. solaris) where that crashes – Ingo Leonhardt Feb 19 '15 at 13:33