【发布时间】:2014-02-05 11:29:33
【问题描述】:
本题要求在不使用<string>头文件的情况下合并两个字符串(前面较长的字符串,较长的字符串后面较短的字符串)。输入的每个字符串不能超过20个字符。
我的逻辑是:
- 先用
strlen得到str1和str2的长度,- 使用
str3存储较长的字符串,使用str4存储较短的字符串。- 将
str3和str4添加到str5
这是我的代码:
#include<iostream>
using namespace std;
int main()
{
// combine two strings , longer in the front, and shorter
// after it. do not use strcat
char str1[20],str2[20],str3[20],str4[20],str5[40];
// str1 and str2 stores original data, str3 stores longer
// and str4 stores shorter, str5 stores total
int j=0;
cin.getline(str1,20);
cin.getline(str2,20);
if(strlen(str1)<=strlen(str2))
// give longer string value to str3,shorter to str2
{
for (int i=0;i<20;i++)
{
str3[i]=str2[i];
str4[i]=str1[i];
}
}
else
{
for (int i=0;i<20;i++)
{
str3[i]=str1[i];
str4[i]=str2[i];
}
}
for(j=0;str3[j]!='\0';j++)
{
str5[j]=str3[j];
}
for(int i=j;i<40;i++)
for(int m=0;m<20;m++)
{
str5[i]=str4[m];
}
cout<<str5<<endl;
return 0;
}
这是输出:
我的问题是什么?两个字符串之间的那些字符是什么?谢谢!!
【问题讨论】:
-
有什么理由不能使用
std::string? -
问题要求不要使用 std::string 标头,也许是为了练习循环?
-
我对@987654333@ 的东西不是很熟悉,但是你看过
strcpy()吗? -
那是 c++ 还是 c 课程?
-
区别很复杂,但本质上c++包含了c的所有内容,并用对象扩展了它。作为学习者,您最好使用 c++ 并使用标准库,这就是人们建议您使用 std::string 而不是 char* 的原因。