题目要求在不使用<string>
的情况下组合两个字符串(较长的字符串在前面,较短的字符串在较长的字符串后面)头文件。输入的每个字符串不能超过20个字符。
我的逻辑是:
- first use
strlen
to get the length of thestr1
andstr2
,- use
str3
to store the longer string, andstr4
to store the shorter.- add
str3
andstr4
tostr5
这是我的代码:
#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
:
#include <iostream>
#include <string>
int main() {
std::string a;
getline(std::cin, a);
std::string b;
getline(std::cin, b);
// Ensure that the longer string goes to the front.
if (a.size() < b.size());
swap(a, b);
std::string result = a + b;
std::cout << result << '\n';
// Or, simply:
std::cout << a << b << '\n';
}
这里的信息是,尽管 C++ 有一些怪癖,但如果您依赖它的库而不是从头开始实现每个低级操作,它就是一种非常高级的语言。
关于c++ - 如何组合两个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21576007/