简体   繁体   English

c - 如何将字符串分成多个部分并存储到C中的数组中?

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

I have a text file that lists some groceries and information about them.我有一个文本文件,其中列出了一些杂货和有关它们的信息。 Looks something like this:看起来像这样:

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

Here's my code that I've used that allows me to reference each individual line:这是我使用的代码,它允许我引用每一行:

#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;
}

For instance, if I print line[1], I will get "Chicken 1kg 7.21 7.50".例如,如果我打印 line[1],我会得到“Chicken 1kg 7.21 7.50”。 What I need to do however, is separate each string into their individual parts.然而,我需要做的是将每个字符串分成各自的部分。 So if I call something like line[1][0], I will get only "Chicken" as a result.因此,如果我调用 line[1][0] 之类的东西,结果我只会得到“Chicken”。 I've tried using strtok(line[i], " ") in some for loops and other things like that, but I'm really stumped about how to apply it to this code.我试过在一些 for 循环和其他类似的东西中使用 strtok(line[i], " ") ,但我真的很困惑如何将它应用于这段代码。

you can write a function (str_to_word_array) this is my str_to_word_array func https://github.com/la-montagne-epitech/mY_Lib_C/blob/master/my_str_to_word_array.c it's take a string and a separator( " " for your case), you have to stock the result in char **, just like this:你可以写一个函数(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);

SOLVED:解决了:

With the help of brahimi haroun in the comments, i made a separate function to perform the task seperately and it works great.在评论中的 brahimi haroun 的帮助下,我创建了一个单独的函数来单独执行任务,并且效果很好。 I thought I would share it here:我想我会在这里分享它:

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];
}

Now, with my original code, if you call get_column_item(line[1], 0);现在,使用我的原始代码,如果您调用 get_column_item(line[1], 0); It will return the first item in that row, so it will return "Chicken".它将返回该行中的第一项,因此它将返回“Chicken”。

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

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