my_strcat_array(char *str,char*arr);形式参数自定义,将array1、array2中的数据连接到str数组中:array1:"hello" array2:"world" -> str:helloworld
//my_strcat_array(char *str,char*arr);形式参数自定义,将arr中的数据连接到str数组中:"hello""world" -> str:helloworld
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>
void my_strcat_array(char *str,char *array1,char *array2)//定义三个数组,array1用来存放hello,array2用来存放world,str作为大数组用来连接两个数组
{
assert(str != NULL && array1 != NULL && array2 != NULL);
for(int i = 0;i < strlen(array1);++i){
str[i] = array1[i];
}
for(int i = 0;i < strlen(array2);++i){
str[strlen(array1) + i] = array2[i];
}
}
int main()
{
char array1[] = "hello";
char array2[] = "world";
char str[5];
my_strcat_array(str,array1,array2);
printf("%s ",str);
return 0;
}
如图为运行结果:
输出完成
如图所示,程序成功连接两个数组,存放进了str数组中并输出。
使用字符串头文件更改函数的代码为:
void my_strcat_array(char *str,char *array)
{
assert(str != NULL && array != NULL);
int len = strlen(str);
for(int i = 0;array[i] != '\0';i++){
str[len + i] = array[i];
}
}
经过优化,此方法只需要开辟两个数组,相比较上面的代码简便了不少。
如图所示为程序运行结果:
输出完成
利用指针:
#include<stdio.h>
#include<iostream>
#include<assert.h>
void my_strcat(char *message1,char *message2)
{
assert(message1 != nullptr && message2 != nullptr);
char *p = message1;
char *q = message2;
assert(p != nullptr && q !=nullptr);
while(*p){//此循环存在的原因:当p指针还停留在第一个字符串时,一直向后迁移,直到到达第一个字符串的末尾
p++;
}
while(*q != '\0'){//跳出第一个循环之后,当指针没有到达第二个字符串的末尾时
*p++ = *q++;//将第二个字符串的字符添加在第一个字符串的后面,循环。
}
}
int main()
{
char message1[100] = {0};
char message2[100] = {0};
printf("Please input your first string: \n");
scanf("%s",message1);
printf("Please input your second string: \n");
scanf("%s",message2);
my_strcat(message1,message2);
printf("The string you connected is %s\n",message1);
return 0;
}
如图我输入hello和world,运行结果为:
连接字符串成功