我是新来的,也是 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/