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

标签 c++ string

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

相关文章:

c++ - 如何从 PowerShell 获取 CreateTransaction 地址

c++ - 为什么 char** 不能作为 C++ 中以下函数的返回类型?

c++ - 有没有Visual Studio 2008 运行时版本的总结?

c++ - 难以实现带有时间限制代码的类(C++)

Python,从字符串中删除所有html标签

c++ - Const std::filesystem::path 引用常量不受尊重,这是我做错的吗?

.net - vb.net - 将字符串编码为 UTF-8

ios - 设置字符串/.text 的最大长度

string - 使用字符串中的名称创建变量

xcode - Swift 2.0 中如何获取另一个字符串中两个文本 block 之间的子字符串