/* Write a program that would mix-and-merge two given strings (s1 and s2) into string s3 as follows:
first character of s1, first character of s2, second character of s1, second character of s2, etc. */
但是我的代码的问题是:如果我键入S1 "John"
,然后S2 "Stevens"
结果将是= JSothenv e n s.
如何停止检查如果一个字符串空指数
如何解决其中一个字符串结束后留下的空格?
我认为我会修复它的方式是我会检查与ifs我在下面的for循环要查看索引是否为null或'\ 0'但不起作用,因为字符串保存随机值在字符串结束后。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1, s2;
string s3;
int i; // For index
int j = 0; // For second index and loop checking
cout << "Type first string: ";
getline(cin, s1);
cout << "Type second string: ";
getline(cin, s2);
s3.resize(s1.size() + s2.size() + 100); // The + 100 is used so we have space for all the characters. The + 100 is not needed if i fix my problem.
for(i = 0; j <= s1.size(); i += 2)
{
if(s1[j] == null) // With what do i check it?
{
break;
}
else
{
s3[i] = s1[j];
++j;
}
}
j = 0;
for(i = 1; j <= s2.size(); i += 2)
{
if(s2[j] == null)
{
break;
}
else
{
s3[i] = s2[j];
}
++j;
}
for(i = 0; i <= s3.size(); ++i)
{
cout << s3[i];
}
return 0;
你的第一段很混乱。请重新阅读并尝试考虑如何使其更清晰。提供一套完整的示例输入和输出将有所帮助。 – 2014-12-19 06:37:36
也许你的意思是说:“给定两个输入字符串,我想通过交织输入字符串的字符来产生第三个字符串,例如,给定”DOG“和”章鱼“,我想产生.. 。“ – 2014-12-19 06:40:15
好的,谢谢我会这么做:)现在编辑更好吗? – Johnson 2014-12-19 06:40:44