Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse simple string in C?

Tags:

c

parsing

I have a string with the following format:

start 123

I am parsing it that way:

if (strstr(line, "start") == line) {
    int number = -1;

    if (sscanf(line + strlen("start "), "%d", &number) == 1) {
        printf("start %d\n", number);
    }
}

Is there any better way in C?

like image 735
Петр Широков Avatar asked Apr 26 '26 10:04

Петр Широков


1 Answers

yes you can use only this:

if (sscanf(line, "start %d", &number ) == 1) {

no need for

if (strstr(line, "start") == line) {

any more

If you want to check more: Check that there is no extra characters after the number , then you can use the following format:

char c;
if (sscanf(line, "start %d%c", &number,  &c) == 1) {

Note: the above formats (and even yours) do not check that there is only 1 space between "start" and the number. so if your string is something like "start \t 45" then the if will return true

like image 125
MOHAMED Avatar answered Apr 28 '26 10:04

MOHAMED



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!