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

标签 c

我必须阅读在 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/

相关文章:

c - 读取以零开头的 int 并将其存储到 C 中的数组中

c - 小端与大端的类型转换

c - 使用来自 C 的系统调用,我如何获得 CPU 的利用率?

android - 如何在基于 Cordova 的 Android 应用程序中使用 C 库

c - 我应该在 C 中的 basename/dirname 之后释放 strdup 指针吗?

c++ - Int(1digit) 到 char 没有任何功能

c - 访问结构的副本。我收到错误 : request for member ‘count’ in something not a structure or union

c - 用于测试错误处理程序的错误 C 代码

c - 从套接字读取缓冲区

c - 同时使用 rand() 和 rand_r() : is this simple example correct?