【问题标题】:How to split a text into two dimensional array in c如何在c中将文本拆分为二维数组
【发布时间】:2021-04-08 23:47:50
【问题描述】:

我正在尝试拆分此字符串:

这是一个文本文件
找猫这个词
该程序还应该打印猫
还有 crat 和 lcat 但它不应该
打印单词 caats

放入一个二维数组,使得文本中的每一行都是数组中的一行。
例如:

lines[0][0] = 't'
lines[0][1] = 'h'

等等。现在,这是我的代码:

void print_lines(char txt[]){
    char lines[SIZE][SIZE];
    int num_of_lines = fill_lines(txt, lines);
    printf("lines: %d\n",num_of_lines );
    int i;
    for (i = 0; i < num_of_lines; i++)
    {   
        printf("%s\n", lines[i]);
    }
}

int fill_lines(char txt[], char lines[][]){
        char copy[strlen(txt)];
        memcpy(copy, txt, strlen(txt));
        char *line = strtok(copy, "\n");

        int i = 0;
        while(line != NULL){
            strcpy(lines[i][0], line);
            line = strtok(NULL, "\n");
            i++
        }
    return i + 1;
}

我目前正在处理的问题是strcpy(lines[i], line) 中的一个错误,内容如下:

表达式必须是指向完整对象类型的指针

我也试过memcpy(lines[i], line, strlen(line))

任何帮助将不胜感激。

【问题讨论】:

  • 您的问题是 fill_lines 函数的参数语法错误。
  • 再看一遍后,我发现整个代码似乎不是C 语言。

标签: arrays c string


【解决方案1】:

我认为这应该适合你 这里我用'\n'作为分隔符

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

char **str_split(char *a_str, const char a_delim)
{
    char **result = 0;
    size_t count = 0;
    char *tmp = a_str;
    char *last_comma = 0;
    char delim[2];
    delim[0] = a_delim;
    delim[1] = 0;

    /* Count how many elements will be extracted. */
    while (*tmp)
    {
        if (a_delim == *tmp)
        {
            count++;
            last_comma = tmp;
        }
        tmp++;
    }

    /* Add space for trailing token. */
    count += last_comma < (a_str + strlen(a_str) - 1);

    /* Add space for terminating null string so caller
       knows where the list of returned strings ends. */
    count++;

    result = malloc(sizeof(char *) * count);

    if (result)
    {
        size_t idx = 0;
        char *token = strtok(a_str, delim);

        while (token)
        {
            assert(idx < count);
            *(result + idx++) = strdup(token);
            token = strtok(0, delim);
        }
        assert(idx == count - 1);
        *(result + idx) = 0;
    }

    return result;
}

int main()
{
    char text[] = "this is a text file\nlooking for the word cat\nthe program should print also cats\nand crat and lcat but it shouldn’t\nprint the word caats";
    char **tokens;

    printf("ORIGINAL TEXT:\n%s\n\n", text);

    tokens = str_split(text, ',');

    if (tokens)
    {
        int i;
        for (i = 0; *(tokens + i); i++)
        {
            printf("%s\n", *(tokens + i));
            free(*(tokens + i));
        }
        printf("\n");
        free(tokens);
    }

    return 0;
}

【讨论】:

  • 非常感谢!这样就完成了工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-24
  • 2016-03-15
  • 2016-08-10
  • 2020-03-19
相关资源
最近更新 更多