简体   繁体   English

在C中将一个字符串分成一个子字符串,然后将该子字符串分成另一个字符串

[英]Separating a string into a substring then that substring into another string in C

I have to read the arguments that I introduce when I run a program on linux. 我必须阅读在Linux上运行程序时引入的参数。

./myprog 10 20 30, 20 54 12, 31 42 51

I have a problem finding out how to separate the arguments into a substring and then that substring in other string. 我在找出如何将参数分成一个子字符串然后在另一个字符串中将该子字符串分开时遇到问题。

10 20 30, 20 54 12, 31 42 51

I want to separate this string into another string with "," being the separator and then that substring to separate into another string with " " being the separator. 我想将此字符串分隔为以“,”为分隔符的另一个字符串,然后将该子字符串分隔为以“”为分隔符的另一个字符串。

 a[0]="10 20 30"
 a[1]="20 55 12"
 a[2]="31 42 51"

Then I want it to be like that: 然后我希望它像这样:

 b[0]="10" b[1]="20" b[2]="30" and so on...

Here I make this code to separate the arguments into a substring. 在这里,我编写此代码将参数分成一个子字符串。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    char *str = "10 20 30, 20 54 12, 31 42 51";
    char **a = calloc(sizeof(char*),strlen(str));
    int x = 0;
    int y = 0;
    int i = 0;

    while (str[i] != '\0')
    {
        x = 0;
        a[y] = calloc(sizeof(char),9);
        while(str[i] != ',' && str[i] != '\0')
        {
            a[y][x] = str[i];
            i++;
            x++;
        }
        y++;
        i += 2;
    }
    //this code below for test
    y--;
    for (int t = 0; t < y; t++)
            printf("%s\n",a[t]);

}

now try to make the other one :). 现在尝试制作另一个:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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