簡體   English   中英

c - 如何將字符串分成多個部分並存儲到C中的數組中?

[英]How to separate a string into parts and store into an array in C?

我有一個文本文件,其中列出了一些雜貨和有關它們的信息。 看起來像這樣:

Round_Steak 1kg 17.38 18.50
Chicken 1kg 7.21 7.50
Apples 1kg 4.25 4.03
Carrots 1kg 2.3 2.27

這是我使用的代碼,它允許我引用每一行:

#include <stdio.h>
#include <string.h>

#define Llimit 100
#define Rlimit 10 

int main()
{
    //Array Line gets each line from the file by setting a limit for them and printing based on that limit.
    char line[Rlimit][Llimit];
    FILE *fp = NULL; 
    int n = 0;
    int i = 0;

    fp = fopen("food.txt", "r");
    while(fgets(line[n], Llimit, fp)) 
    {
        line[n][strlen(line[n]) - 1] = '\0';
        n++;
    }
    
    printf("%s", line[1]);
    
    fclose(fp);
    return 0;
}

例如,如果我打印 line[1],我會得到“Chicken 1kg 7.21 7.50”。 然而,我需要做的是將每個字符串分成各自的部分。 因此,如果我調用 line[1][0] 之類的東西,結果我只會得到“Chicken”。 我試過在一些 for 循環和其他類似的東西中使用 strtok(line[i], " ") ,但我真的很困惑如何將它應用於這段代碼。

你可以寫一個函數(str_to_word_array)這是我的 str_to_word_array func https://github.com/la-montagne-epitech/mY_Lib_C/blob/master/my_str_to_word_array.c它需要一個字符串和一個分隔符(“”對於你的情況) ,您必須將結果存儲在 char ** 中,就像這樣:

char *line; // type of the element
char separator // type of the element
char **tab = my_str_to_word_array(line, separator);

解決了:

在評論中的 brahimi haroun 的幫助下,我創建了一個單獨的函數來單獨執行任務,並且效果很好。 我想我會在這里分享它:

char **get_column_item(char *lines, int column)
{
    int i = 0;
    char *p = strtok(lines, " ");
    char *array[4];

    while (p != NULL)
    {
        array[i++] = p;
        p = strtok(NULL, " ");
    }

    printf("%s\n", array[column]);

    return array[column];
}

現在,使用我的原始代碼,如果您調用 get_column_item(line[1], 0); 它將返回該行中的第一項,因此它將返回“Chicken”。

暫無
暫無

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

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