在C ++中将字符串合并在一起,而不是添加到合并中

时间:2018-11-11 15:40:53

标签: c++ string merge

我在用C ++将两个字符串合并在一起时遇到麻烦,这是我的问题的一些示例代码

for (int i = 0; i < outputString.length(); i++) {
    char letter = outputString.charAt(i);
    //The rest of you code here
}

3 个答案:

答案 0 :(得分:0)

首先,我假设输入字符串中不应存在空格,否则输出将看起来很奇怪。

C ++中有一个预定义的merge()函数或方法,您必须自己编写。这应该为您提供一些入门帮助(伪代码):

string mergeStrings(string1, string2)
{
    string output = "";  // empty string. The loop below will add to it.
    output.reserve(string1.length);   // pre-allocate memory for performance

    // add two chars per loop iteration, one from string1, one from string2:
    for(i=0; i < min(string1.length, string2.length)/2; i+=2)
    {
        output += string1[i];
        output += string2[i+1];
    }

    return output;
}

请用笔和纸检查循环边界是否正确:那里可能有一个“ off by one”错误。

此外,您还需要考虑如果输入字符串的长度不同,该函数应该怎么做!

答案 1 :(得分:0)

两个字符串之间的operator +创建一个新字符串,该字符串是两个输入字符串的串联。

您应该创建自己的函数。这是一个示例,其中"_"中的字符str1str2中的相应字符代替。 (假设str1str2的大小相同)

string merged = str1;
for (int i=0; i < str1.size(); ++i)
{
    if (str1[i] == '_')
            merged[i] = str2[i];
}

答案 2 :(得分:0)

您可以创建一个函数,该函数返回合并的字符串,以在另一个字符串小于另一个字符串时进行验证,并使用“合并标识符”(它将替换为特殊字符),如下所示:

//----------------function declaration----------------
std::string merge_strings(std::string strA, std::string strB, char mergeIdentifier);
int greater_number(int numberA, int numberB);
int smaller_number(int numberA, int numberB);

int main()
{
    std::string str1 = "H _ l _ o";
    std::string str2 = " _ e _ l _";

    std::cout << merge_strings(str1, str2, '_'); //outputs H e l l o

    return 0;
}

//-----------------function definition----------------
std::string merge_strings(std::string strA, std::string strB, char mergeIdentifier)
{
    std::string merged = "";

    int greaterIndex = greater_number(strA.size(), strB.size());
    int smallerIndex = smaller_number(strA.size(), strB.size());

    for(int currentCharIndex = 0; currentCharIndex < greaterIndex; currentCharIndex++)
    {
        if(currentCharIndex < smallerIndex)
        {
            if(strA[currentCharIndex] == mergeIdentifier)
                merged += strB[currentCharIndex];
            else if(strA[currentCharIndex] != mergeIdentifier)
                merged += strA[currentCharIndex];
        }
        else
            break;
    }

    return merged;
}


int greater_number(int numberA, int numberB){return numberA > numberB? numberA : numberB;}
int smaller_number(int numberA, int numberB){return numberA < numberB? numberA : numberB;}

如果其中一个字符串比另一个字符串小,它将合并较小字符串的大小,但是您可以通过检查哪个字符串更长,然后将合并后的字符串大小中的字符添加到末尾来添加缺少的字符较长的字符串。