繁体   English   中英

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

[英]How to copy a string to a 2D array in c

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


#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]!='\0'; 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)?

您可能正在寻找的是来自<string.h>strtok 正如tadman在评论中所建议的那样,我还将在以下代码片段中将row替换为rows ,将column替换为columns

/* 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 function 可能会简化为:

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

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

Output:

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

暂无
暂无

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

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