如何从字符串文字创建多维数组

时间:2016-11-14 10:55:13

标签: c multidimensional-array string-literals

我是新来的,我也是C的新手。 我有以下指针ptr指向String Literal

const char *ptr = "Hello my dear World";

我需要做的是创建一个多维数组,其中应该包含那些应该产生类似内容的单词:

char arr[MAX_WORD][MAX_SIZE_OF_WORD] = {"Hello", "my", "dear", "World"};

到目前为止我所拥有的是:

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

#define MAX_WORD 4
#define MAX_SIZE_OF_WORD 6

int main(void){
    const char *ptr = "Hello my dear World";
    char arr[MAX_WORD][MAX_SIZE_OF_WORD] = {0};

    while ( *ptr != '\0'){
        /* code here */
        ptr++;
    }

    size_t len = sizeof arr / sizeof *arr;
    for (size_t x = 0 ; x < len ; x++){
        printf("%s",arr[x]);
        printf("\n");
    }
}

我的逻辑是迭代ptr直到我到达'\0'并将这些字词复制到char arr[][]中,但问题是,我不知道该怎么做。

如何在ptr内复制arr[][]的内容?

1 个答案:

答案 0 :(得分:0)

你在这里。

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

#define MAX_WORD 4
#define MAX_SIZE_OF_WORD 6

void split_to_array( char ( *a )[ MAX_SIZE_OF_WORD ], size_t n, const char *s )
{
    for ( size_t i = 0; *s != '\0' && i < n; i++ )
    {
        while ( isblank( ( unsigned int )*s ) ) ++s;

        if ( *s )
        {
            const char *last = s;
            while ( ++last && !isblank( ( unsigned char )*last ) );

            size_t length = ( size_t )(last - s + 1 < MAX_SIZE_OF_WORD ? 
                            last - s + 1 :
                            MAX_SIZE_OF_WORD );

            strncpy( a[i], s, length );
            a[i][length -1] = '\0';

            s = last;
        }
    }
}

int main(void) 
{
    const char *ptr = "Hello my dear World";
    char arr[MAX_WORD][MAX_SIZE_OF_WORD] = {0};

    split_to_array( arr, MAX_WORD, ptr );

    for ( size_t i = 0; i < MAX_WORD; i++ ) puts( arr[i] );

    return 0;
}

程序输出

Hello
my
dear
World