gpt4 book ai didi

c++ - 如何在字符串索引为空时停止检查

转载 作者:行者123 更新时间:2023-11-28 00:20:56 26 4
gpt4 key购买 nike

/* 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.

如何修复其中一个字符串结束后留下的空格?

我想我会修复它的方法是我会检查我在下面的 for 循环中的 ifs 以查看索引是否为 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;

最佳答案

试试这个:

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char const *argv[])
{
string s1, s2, s3;

int i,j,k;
cout << "Type first string: ";
getline(cin, s1);
cout << "Type second string: ";
getline(cin, s2);
s3.resize(s1.size()+s2.size());

for(i = 0, j = 0, k = 0; j < s1.size() && k < s2.size(); i++) {
if(i & 1) {
s3[i] = s2[k++];
} else {
s3[i] = s1[j++];
}
}
if(j == s1.size()) {
while(k < s2.size()) {
s3[i++] = s2[k++];
}
} else {
while(j < s1.size()) {
s3[i++] = s1[j++];
}
}

cout << s3 << endl;

return 0;
}

关于c++ - 如何在字符串索引为空时停止检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27560828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com