C split a char array into different variables

后端 未结 7 1086
不思量自难忘°
不思量自难忘° 2020-12-03 08:31

In C how can I separate a char array by a delimiter? Or is it better to manipulate a string? What are some good C char manipulation functions?

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-03 08:55

    In addition, you can use sscanf for some very simple scenarios, for example when you know exactly how many parts the string has and what it consists of. You can also parse the arguments on the fly. Do not use it for user inputs because the function will not report conversion errors.

    Example:

    char text[] = "1:22:300:4444:-5";
    int i1, i2, i3, i4, i5;
    sscanf(text, "%d:%d:%d:%d:%d", &i1, &i2, &i3, &i4, &i5);
    printf("%d, %d, %d, %d, %d", i1, i2, i3, i4, i5);
    

    Output:

    1, 22, 300, 4444, -5

    For anything more advanced, strtok() and strtok_r() are your best options, as mentioned in other answers.

提交回复
热议问题