簡體   English   中英

在C中將一個字符串分成一個子字符串,然后將該子字符串分成另一個字符串

[英]Separating a string into a substring then that substring into another string in 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]);

}

現在嘗試制作另一個:)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM