RoadRunner RoadRunner - 2 months ago 7
C Question

Splitting string sequence into integers

How do you split a string:

char *mystring = "12345"


into an integer array which looks like this:

[1, 2, 3, 4, 5]


I have tried something like the code below, but I'm not entirely sure if it's reliable, and I think it will be easy to break. This is the code:

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

int
main(void) {
char *mystring = "12345";
int string_size, i, length;

string_size = strlen(mystring);

int values[string_size];

for (i = 0; mystring[i] != '\0'; i++) {
values[i] = mystring[i] - 48;
}

length = sizeof(values)/sizeof(*values);

for (i = 0; i < length; i++) {
printf("%d ", values[i]);
}

return 0;
}


Which outputs:

1 2 3 4 5


Is there a more C like way I can do this?

Answer

The odd thing I see, which isn't itself a problem, is that you calculate the length of the string/array three different ways:

string_size = strlen(mystring);

for (i = 0; mystring[i] != '\0'; i++) {

length = sizeof(values)/sizeof(*values);

where just one method is sufficient:

#include <stdio.h>
#include <string.h>

int main(void) {
    char *mystring = "12345";

    size_t length = strlen(mystring);

    int values[length];

    for (int i = 0; i < length; i++) {
        values[i] = mystring[i] - '0';
    }

    for (int i = 0; i < length; i++) {
        printf("%d ", values[i]);
    }

    printf("\n");

    return 0;
}
Comments