《C++程序设计语言》6.6_13 字符串的拼接

来源:互联网 发布:淘宝仓管是做什么的 编辑:程序博客网 时间:2024/05/20 17:42
/*--------------------------------------------------写一个函数cat(),它取两个C风格字符串为参数,返回一个字符串,该字符串是两个参数串的拼接。利用new为这个结果取得存储。-------------------------------------------------*/#include <iostream>using std::cout;using std::cin;using std::endl;const int N = 20;char* create(){char ch;char *p = new char [N];int i = 0;for (; i < N-1; i++){ch = cin.get();if (ch != '\n')p[i] = ch;elsebreak;}p[i] = '\0';return p;}void show(char* sch){puts(sch);}char* cat(char* ch1, char* ch2){int l = strlen(ch1) + strlen(ch2);char *cch = new char[l+1];int i = 0;for (; i < strlen(ch1); i++)cch[i] = ch1[i];for (int j = 0; i < l; i++, j++)cch[i] = ch2[j];cch[i] = '\0';return cch;}int main(){char *ch1, *ch2, *ch3;cout << "Please input first C-string:\n";ch1 = create();show(ch1);cout << "Please input second C-string:\n";ch2 = create();show(ch2);cout << "Splice the two string:\n";ch3 = cat(ch1, ch2);show(ch3);delete [] ch1, ch2, ch3;return 0;}