如何在c中将字符串复制到二维数组

How to copy a string to a 2D array in c

我想创建一个 c 程序,当用户输入这样的单词时:“some,words, in, c, proramming。”程序将单词保存在字符串“str”中,然后动态创建一个二维数组并将单词复制到二维数组中:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <math.h>
#include <conio.h>

void freeMememory(int**array, int row){
    for(int i=0;i<row;i++)
        free(array[i]);
    free(array);
}

int lettersCount(char *arr){
    int space=0, letters=0;
        do{
        if(*arr !=' '&& *arr!='\t' && *arr!=','&& *arr!='.'){
          letters =letters+1;
        }
        ++arr;
        }while(*arr);

    return letters;
}

int wordCount(char *arr){
    int space=0, words=0;
    for(int i=0; arr[i]!='[=10=]'; i++){
        if(arr[i] ==' '|| arr[i]=='\t'|| arr[i]=='\n'||arr[i]==','||arr[i]=='.'){
          space++;
        }
        if(space>0){
            words++;
            space=0;
        }
    }

    return words;
}
int main    (){
    char arr[100];
    int i, j, row, column;

    scanf("%[^\n]s", &arr);
    int *words = wordCount(arr);
    int *letters = lettersCount(arr);
    row=words;
    column=letters;

    int **ptr = (int **)malloc(row*column*sizeof(int));
    for(i=0;i<row;i++){ptr[i]=(int*)malloc(column*sizeof(int));}

    /*

    //how should I write here to copy only words from arr to ptr?
    like this:

    arr = "some words, two,three,four."
    
    ptr = {
       "some", "words", "two", "", "three", "four",
      }
     
    */

    freeMememory(ptr, row);
    return 0;}


关于如何仅将字符串中的单词复制到二维数组中而不复制(句点、空格、cammas)有什么想法吗?

您可能正在寻找的是评论中的strtok from <string.h>. I will also replace row with rows and column with columns in the following code snippet, as suggested by tadman

/* no need to cast `malloc` */
char *ptr[rows];
for (int i = 0; i < rows; ++i) {
    ptr[i] = malloc(columns);
    if (!token) {
        fprintf(stderr, "Error: memory allocation failed\n");
        exit(EXIT_FAILURE);
    }
}

const char *delims = " \t\n,.";

/* second argument are delimiters */
strcpy(ptr[0], strtok(arr, delims));
for (int i = 1; i < rows; ++i)
    strcpy(ptr[i], strtok(NULL, delims));

我还建议简化您的功能。例如,您的 wordCount 函数可能可以简化为:

int count_words(char *str, const char *delims)
{
    words = 1;
    for (int i = 0; str[i] != '[=11=]'; ++i)
        if (strchr(delims, str[i]))
            ++words;
    return words;
}

函数 count_words 可以这样调用:

const char *delims = " \t\n,.";
int words = count_words(arr, delims);

首先请注意,您的代码未使用二维数组。它使用一个字符指针数组,每个指针指向一个字符数组。这是一个不同的东西,但它可以以几乎相同的方式使用。

下面是一个使用strtok分割输入字符串的实现。此外,它使用 realloc 使字符指针数组在找到新单词时增长。最后它使用一个哨兵(即 NULL)来指示单词结束。

代码很简单,但是性能很差。

示例:

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

char** split(const char* str)
{
    if (str == NULL) exit(1);

    // Copy input string as strtok changes its input    
    char* str_cpy = malloc(strlen(str) + 1);
    if (str_cpy == NULL) exit(1);
    strcpy(str_cpy, str);
    
    unsigned num_rows = 0;
    char** arr = NULL;

    // Get first token
    const char *delims = " \t\n,.";
    char* ptr = strtok(str_cpy, delims);
    while (ptr)
    {
        // Allocate one more row
        arr = realloc(arr, (num_rows + 1) * sizeof *arr);
        if (arr == NULL) exit(1);
        
        // Allocate memory for one more word
        arr[num_rows] = malloc(strlen(ptr) + 1);
        if (arr[num_rows] == NULL) exit(1);
        strcpy(arr[num_rows], ptr);
        ++num_rows;

        // Get next token
        ptr = strtok(NULL, delims);
    }

    // Add a sentinel to indicate end-of-words
    arr = realloc(arr, (num_rows + 1) * sizeof *arr);
    if (arr == NULL) exit(1);
    arr[num_rows] = NULL;
    
    free(str_cpy);    
    return arr;
}

int main(void) 
{
    char* str = "some,words, in,    c, programming.";
    char** arr = split(str);
    
    printf("Original string: %s\n", str);
    for (int i=0; arr[i] != NULL; ++i)
    {
        printf("Word[%d]: %s\n", i, arr[i]);
    }

    // Free array       
    for (int i=0; arr[i] != NULL; ++i)
    {
        free(arr[i]);
    }
    free(arr);
    
    return 0;
}

输出:

Original string: some,words, in,    c, programming.
Word[0]: some
Word[1]: words
Word[2]: in
Word[3]: c
Word[4]: programming