C如何实现将一个字符数组赋值给其它的多个字符数组
时间: 2024-05-01 11:21:52 浏览: 9
可以使用循环遍历字符数组,并将每个字符依次赋值给目标字符数组中对应的元素。示例代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "hello world";
char target1[6], target2[6], target3[6];
int i;
for (i = 0; i < 5; i++) {
target1[i] = source[i];
}
target1[5] = '\0';
for (i = 5; i < 10; i++) {
target2[i-5] = source[i];
}
target2[5] = '\0';
for (i = 10; i < strlen(source); i++) {
target3[i-10] = source[i];
}
target3[strlen(source)-10] = '\0';
printf("source: %s\n", source);
printf("target1: %s\n", target1);
printf("target2: %s\n", target2);
printf("target3: %s\n", target3);
return 0;
}
```
在上面的示例代码中,首先定义了一个字符数组 `source`,然后定义了三个目标字符数组 `target1`、`target2` 和 `target3`,它们的长度都为 6。接着使用 for 循环遍历 `source` 数组,将其中的字符依次赋值给三个目标数组中对应的元素。需要注意的是,为了将字符数组转换为字符串,需要在每个目标数组的最后一个元素处添加 '\0',表示字符串的结束符。
当程序运行时,输出结果如下:
```
source: hello world
target1: hello
target2: worl
target3: d
```
可以看到,将一个字符数组赋值给其它的多个字符数组已经成功实现了。