本文实例为大家分享了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 *ch1 = "string_"; char * ch2 = "_contact"; char *result = NULL; result = str_contact(ch1,ch2); 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 *ch1 = "str_cpy"; char *ch2; char *result = strcpy(ch2,ch1); 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; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持免费资源网。