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

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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值