简体   繁体   中英

Subtracting a piece of information from a char array in C

I am currently working on a piece of code and I am not sure how to tackle this problem. Ill explain the situation:

The goal of this code is to make a "dynamic" matrix in C. Using "fgets" I get a char array, my code interprets the first line as a char array. However there are more lines I am at this point only interested in the first one, all the other lines just contain the information I need to store.

The reason why I am only interested in the first line is because it contains the information on how big the matrix needs to be to fit all the information below. The information comes in a pattern, it is always in the form of x,y. The x and y are not bound by each other, the x could be for instance 10 times smaller or greater then the y. Also the location of the information on the line is not set, it could be floating on the right of the screen or on the left.

Is there any form, like regex in java, that I could use to filter the information? For examples look for "," in the first line and when it is found check the right and left side from the "," all the way to the first white space and store those both values in a variable.

example:

[                   14,10            ]

the outcome would be then:

int rowSize = 14;
int columnSize = 10;

Why not search for the first valid decimal character?

#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>

char *first_digit(const char *s)
{
    while (!isdigit(*s)) s++;
    return s;
}


int main()
{
    const char *line = "[             14,      10        ]";
    int n, k;

    const char *first = first_digit(line);
    const char *end;
    n = strtol(first, &end, 10);

    const char *second = first_digit(end);
    k = strtol(second, NULL, 10);

    printf("n, k = %d, %d\n", n, k);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM