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

标签 c multidimensional-array string-literals

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

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[][] 中,但问题是,我不知道该怎么做。

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

最佳答案

给你。

#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

关于c - 如何从字符串文字创建多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40587047/

相关文章:

java - 无法处理大于 65535 个字符的字符串文字。编译器抛出 IllegalArgumentException

c 处理大文件

json - 在 Swift 5.1 中循环多维/嵌套 JSON 数据

java - For-each并分配给二维数组Java

C 编程。为什么这不起作用?

c - GCC __func__ 被评估为空字符串

c++ - 字符串常量在 C++ 中存在多长时间?

c - 将字符串数组分配给 char **

c - 最近指针不为空时出现空指针取消引用错误

c - 无效函数错误?