小编给大家分享一下C语言实现字符串拼接和拷贝的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

本文实例为大家分享了C语言实现字符串拼接和拷贝的具体代码,供大家参考,具体内容如下

字符串拼接:

#include<stdio.h>#include<stdlib.h>#include<string.h> char *str_contact(const char *,const char *); char *str_contact(const char *str1,const char *str2){ char *result = (char*) malloc(strlen(str1) + strlen(str2) + 1); if(!result) { printf("Error: malloc failed in concat! \n"); exit(EXIT_FAILURE); } char *temp = result; while(*str1 != '\0') { *result++ = *str1++; } while((*result++ = *str2) != '\0') { ; } return temp;} int main(void){ char *ch2 = "string_"; char * ch3 = "_contact"; char *result = NULL; result = str_contact(ch2,ch3); print("result = %s\n",result); free(result); result = NULL; return 0;}

字符串拷贝:

#include<stdio.h>#include<stdlib.h>#include<string.h> char *strcpy(char *dst,const char *src){ assert(*dst != NULL && *src!=NULL); char *temp = dst; while(*src!='\0') { *dst++ = *src++; } *dst = '\0'; return temp;} int main(void){ char *ch2 = "str_cpy"; char *ch3; char *result = strcpy(ch3,ch2); printf("result = %s\n",result); free(result); result = NULL; return 0;}

小编再为大家分享一段之前收藏的代码,感谢原作者的分享。

C++字符串拼接功能描述:实现在字符串末尾拼接字符串

#include <iostream>#include <string>using namespace std;//string& operator+=(const char* str); //重载+= 操作符//string& operator+=(const char c); //重载+= 操作符//string& operator+=(const string& str); //重载+= 操作符//string& append(const char* s); //把字符串s连接到当前字符串结尾//string& append(const char* s, int n); //把字符串的前n个字符赋给当前的字符串//string& append(const string& s); //把字符串s赋给当前字符串//string& append(int n, char c); //用n个字符赋给当前字符串void test01(){ string str1 = "我"; str1 += "爱玩游戏"; cout << "str1 = " << str1 << endl; str1 += ":"; cout << "str1 = " << str1 << endl; string str2 = "LOL DNF"; str1 += str2; cout << "str1 = " << str1 << endl; string str3 = "I"; str3.append(" love "); str3.append("game abcde", 4); //str3.append(str2); cout << "str3 = " << str3 << endl; //lol dnf str3 = i love game str3.append(str2, 4, 3); //从下标4位置开始, 截取3个字符,拼接到字符串末尾 cout << "str3 = " << str3 << endl;}int main(){ test01(); return 0;}

看完了这篇文章,相信你对C语言实现字符串拼接和拷贝的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!