自定义字符串操作
1.字符串拼接
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *str_contact(const char *, const char *);
/**
** C语言实现字符串拼接
**/
int main(void)
{
char *ch1 = "hui_";
char *ch2 = "_heihei";
char *res = NULL;
res = str_contact(ch1, ch2);
printf("res = %s\n", res);
free(res);
res = NULL;
system("pause");
return 0;
}
/**
** 字符串拼接方法
**/
char *str_contact(const char *str1, const char *str2)
{
char *result;
result = (char *)malloc(strlen(str1) + strlen(str2) + 1); //str1的长度 + str2的长度 + \0;
if (!result)
{ //如果内存动态分配失败
printf("Error: malloc failed in concat! \n");
exit(EXIT_FAILURE);
}
strcpy(result, str1);
strcat(result, str2); //字符串拼接
return result;
}
//完全自定义方法
/*方法一,不改变字符串a,b, 通过malloc,生成第三个字符串c, 返回局部指针变量*/
char *join1(char *a, char *b)
{
char *c = (char *)malloc(strlen(a) + strlen(b) + 1); //局部变量,用malloc申请内存
if (c == NULL)
exit(1);
char *tempc = c; //把首地址存下来
while (*a != '\0')
{
*c++ = *a++;
}
while ((*c++ = *b++) != '\0')
{
;
}
//注意,此时指针c已经指向拼接之后的字符串的结尾'\0' !
return tempc; //返回值是局部malloc申请的指针变量,需在函数调用结束后free之
}
return tempc; //返回值是局部malloc申请的指针变量,需在函数调用结束后free之
}