一些简单编程问题的集合(转)

来源:互联网 发布:php工程师收入 编辑:程序博客网 时间:2024/05/19 19:34

c++ 两个字符串连接

输入两个长度不超过100的字符串放入两个不同的字符数组中,而后将两个输入串连接起来(放入第一个字符数组中),并输出结果串以及各串的长度(但不能使用标准库函数strcat及strlen)。

【分析提示】

1、说明:char s1[202], s2[101];并从键盘读入两个字符串放入此二数组中。

2、将s2字符串连接到s1字符串的“后面”(压着s1的"\0"字符往后连接)。连接结束后,一定要往s1串的尾部再放置一个"\0"字符,以表示新的s1串的结束。

【解答程序】

#include<iostream>using namespace std;int main(){char s1[202], s2[101];cout << "Input the first string(Ended with ENTER):" << endl;cin.getline(s1, 100);cout << "Input the second string(Ended with ENTER):" << endl;cin.getline(s2, 100);cout << endl;int i = 0, j = 0;int s1Len, s2Len, catLen;while(s1[i])   i++;s1Len = i;while(s2[j])   s1[i++] = s2[j++];s2Len = j;s1[i] = '\0';catLen = s1Len + s2Len;cout << "The result cat_string is:" << endl;cout << s1 << endl;cout << "First string length = " << s1Len << endl;cout << "Second string length = " << s2Len << endl;cout << "result cat_string length = " << catLen << endl;return 0;}


原创粉丝点击