我必须阅读在 Linux 上运行程序时引入的参数。
./myprog 10 20 30, 20 54 12, 31 42 51
我在找出如何将参数分成子字符串,然后将该子字符串分成其他字符串时遇到问题。
10 20 30, 20 54 12, 31 42 51
我想用“,”作为分隔符将该字符串分隔成另一个字符串,然后将该子字符串分隔成另一个用“”作为分隔符的字符串。
a[0]="10 20 30"
a[1]="20 55 12"
a[2]="31 42 51"
然后我希望它是这样的:
b[0]="10" b[1]="20" b[2]="30" and so on...
最佳答案
这里我编写了这段代码来将参数分隔成子字符串。
#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]);
}
现在尝试制作另一个:)。
关于c - 在C中将一个字符串分成一个子字符串,然后将该子字符串分成另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53626346/