Merging strings together in c++, not adding onto, Merging











up vote
0
down vote

favorite












I am Having trouble merging two strings together in c++, here is some example code of my problem



#include<iostream>

using namespace std;

// I want to add these two strings


string str1 = "H _ l _ o";
string str2 = "_ e _ l _";

//Now if i try add these together


cout << str1 + str2 << endl;


// outputs "H _ l _ o _ e _ l _"




// i Want it to output "H e l l o"

// anyway i could do that? Thanks









share|improve this question


















  • 1




    Welcome to Stack Overflow. Please read the help pages, take the SO tour, read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
    – Some programmer dude
    Nov 11 at 15:41










  • You may iterate throug both strings concurrently with one index. For each index, you check whether first string has a '_' at this index. If so, replace it by character of second string at this index.
    – Scheff
    Nov 11 at 15:47










  • Use cout << Merge(str1, str2) << 'n'; (usually 'n' is better than endl). All you need to do is write string Merge(string const& s1, string const& s2) and you're golden.
    – Eljay
    Nov 11 at 15:51















up vote
0
down vote

favorite












I am Having trouble merging two strings together in c++, here is some example code of my problem



#include<iostream>

using namespace std;

// I want to add these two strings


string str1 = "H _ l _ o";
string str2 = "_ e _ l _";

//Now if i try add these together


cout << str1 + str2 << endl;


// outputs "H _ l _ o _ e _ l _"




// i Want it to output "H e l l o"

// anyway i could do that? Thanks









share|improve this question


















  • 1




    Welcome to Stack Overflow. Please read the help pages, take the SO tour, read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
    – Some programmer dude
    Nov 11 at 15:41










  • You may iterate throug both strings concurrently with one index. For each index, you check whether first string has a '_' at this index. If so, replace it by character of second string at this index.
    – Scheff
    Nov 11 at 15:47










  • Use cout << Merge(str1, str2) << 'n'; (usually 'n' is better than endl). All you need to do is write string Merge(string const& s1, string const& s2) and you're golden.
    – Eljay
    Nov 11 at 15:51













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I am Having trouble merging two strings together in c++, here is some example code of my problem



#include<iostream>

using namespace std;

// I want to add these two strings


string str1 = "H _ l _ o";
string str2 = "_ e _ l _";

//Now if i try add these together


cout << str1 + str2 << endl;


// outputs "H _ l _ o _ e _ l _"




// i Want it to output "H e l l o"

// anyway i could do that? Thanks









share|improve this question













I am Having trouble merging two strings together in c++, here is some example code of my problem



#include<iostream>

using namespace std;

// I want to add these two strings


string str1 = "H _ l _ o";
string str2 = "_ e _ l _";

//Now if i try add these together


cout << str1 + str2 << endl;


// outputs "H _ l _ o _ e _ l _"




// i Want it to output "H e l l o"

// anyway i could do that? Thanks






c++ string merge






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 15:40









MC HELP

1




1








  • 1




    Welcome to Stack Overflow. Please read the help pages, take the SO tour, read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
    – Some programmer dude
    Nov 11 at 15:41










  • You may iterate throug both strings concurrently with one index. For each index, you check whether first string has a '_' at this index. If so, replace it by character of second string at this index.
    – Scheff
    Nov 11 at 15:47










  • Use cout << Merge(str1, str2) << 'n'; (usually 'n' is better than endl). All you need to do is write string Merge(string const& s1, string const& s2) and you're golden.
    – Eljay
    Nov 11 at 15:51














  • 1




    Welcome to Stack Overflow. Please read the help pages, take the SO tour, read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
    – Some programmer dude
    Nov 11 at 15:41










  • You may iterate throug both strings concurrently with one index. For each index, you check whether first string has a '_' at this index. If so, replace it by character of second string at this index.
    – Scheff
    Nov 11 at 15:47










  • Use cout << Merge(str1, str2) << 'n'; (usually 'n' is better than endl). All you need to do is write string Merge(string const& s1, string const& s2) and you're golden.
    – Eljay
    Nov 11 at 15:51








1




1




Welcome to Stack Overflow. Please read the help pages, take the SO tour, read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
– Some programmer dude
Nov 11 at 15:41




Welcome to Stack Overflow. Please read the help pages, take the SO tour, read about how to ask good questions, as well as this question checklist. Lastly learn how to create a Minimal, Complete, and Verifiable Example.
– Some programmer dude
Nov 11 at 15:41












You may iterate throug both strings concurrently with one index. For each index, you check whether first string has a '_' at this index. If so, replace it by character of second string at this index.
– Scheff
Nov 11 at 15:47




You may iterate throug both strings concurrently with one index. For each index, you check whether first string has a '_' at this index. If so, replace it by character of second string at this index.
– Scheff
Nov 11 at 15:47












Use cout << Merge(str1, str2) << 'n'; (usually 'n' is better than endl). All you need to do is write string Merge(string const& s1, string const& s2) and you're golden.
– Eljay
Nov 11 at 15:51




Use cout << Merge(str1, str2) << 'n'; (usually 'n' is better than endl). All you need to do is write string Merge(string const& s1, string const& s2) and you're golden.
– Eljay
Nov 11 at 15:51












3 Answers
3






active

oldest

votes

















up vote
0
down vote













First of all, I'm assuming that the spaces should not be there in your input strings, otherwise the output will look strange.



There's pre-defined merge() function or method in C++, you would have to write it yourself. This should give you some starting help (pseudo-code):



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;
}


Please check using a pen and paper whether the loop boundaries are correct: There might be an "off by one" error there.



Also, you need to think about what the function should do if the input strings have different length!






share|improve this answer




























    up vote
    0
    down vote













    The operator + between two strings creates a new string which is the concatenation of the two input strings.



    You should create your own function. Here is an example where the characters "_" of str1 are replaced by the corresponding characters in str2. (it assumes str1 and str2 have the same size)



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





    share|improve this answer




























      up vote
      0
      down vote













      you can create a function that returns the merged string validating when another string is smaller than the other and using a "merge identifier" which is going to be the special character to replace, something like this:



      //----------------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;}


      If one of the strings is smaller than the other, it will merge just the size of the smaller string but you could just add the missing characters by checking which string is longer and adding the characters from the merged string size to the end of the longer string.






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250340%2fmerging-strings-together-in-c-not-adding-onto-merging%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        0
        down vote













        First of all, I'm assuming that the spaces should not be there in your input strings, otherwise the output will look strange.



        There's pre-defined merge() function or method in C++, you would have to write it yourself. This should give you some starting help (pseudo-code):



        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;
        }


        Please check using a pen and paper whether the loop boundaries are correct: There might be an "off by one" error there.



        Also, you need to think about what the function should do if the input strings have different length!






        share|improve this answer

























          up vote
          0
          down vote













          First of all, I'm assuming that the spaces should not be there in your input strings, otherwise the output will look strange.



          There's pre-defined merge() function or method in C++, you would have to write it yourself. This should give you some starting help (pseudo-code):



          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;
          }


          Please check using a pen and paper whether the loop boundaries are correct: There might be an "off by one" error there.



          Also, you need to think about what the function should do if the input strings have different length!






          share|improve this answer























            up vote
            0
            down vote










            up vote
            0
            down vote









            First of all, I'm assuming that the spaces should not be there in your input strings, otherwise the output will look strange.



            There's pre-defined merge() function or method in C++, you would have to write it yourself. This should give you some starting help (pseudo-code):



            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;
            }


            Please check using a pen and paper whether the loop boundaries are correct: There might be an "off by one" error there.



            Also, you need to think about what the function should do if the input strings have different length!






            share|improve this answer












            First of all, I'm assuming that the spaces should not be there in your input strings, otherwise the output will look strange.



            There's pre-defined merge() function or method in C++, you would have to write it yourself. This should give you some starting help (pseudo-code):



            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;
            }


            Please check using a pen and paper whether the loop boundaries are correct: There might be an "off by one" error there.



            Also, you need to think about what the function should do if the input strings have different length!







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 11 at 15:51









            Geier

            774314




            774314
























                up vote
                0
                down vote













                The operator + between two strings creates a new string which is the concatenation of the two input strings.



                You should create your own function. Here is an example where the characters "_" of str1 are replaced by the corresponding characters in str2. (it assumes str1 and str2 have the same size)



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





                share|improve this answer

























                  up vote
                  0
                  down vote













                  The operator + between two strings creates a new string which is the concatenation of the two input strings.



                  You should create your own function. Here is an example where the characters "_" of str1 are replaced by the corresponding characters in str2. (it assumes str1 and str2 have the same size)



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





                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    The operator + between two strings creates a new string which is the concatenation of the two input strings.



                    You should create your own function. Here is an example where the characters "_" of str1 are replaced by the corresponding characters in str2. (it assumes str1 and str2 have the same size)



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





                    share|improve this answer












                    The operator + between two strings creates a new string which is the concatenation of the two input strings.



                    You should create your own function. Here is an example where the characters "_" of str1 are replaced by the corresponding characters in str2. (it assumes str1 and str2 have the same size)



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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 11 at 15:58









                    Liumatt

                    1335




                    1335






















                        up vote
                        0
                        down vote













                        you can create a function that returns the merged string validating when another string is smaller than the other and using a "merge identifier" which is going to be the special character to replace, something like this:



                        //----------------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;}


                        If one of the strings is smaller than the other, it will merge just the size of the smaller string but you could just add the missing characters by checking which string is longer and adding the characters from the merged string size to the end of the longer string.






                        share|improve this answer



























                          up vote
                          0
                          down vote













                          you can create a function that returns the merged string validating when another string is smaller than the other and using a "merge identifier" which is going to be the special character to replace, something like this:



                          //----------------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;}


                          If one of the strings is smaller than the other, it will merge just the size of the smaller string but you could just add the missing characters by checking which string is longer and adding the characters from the merged string size to the end of the longer string.






                          share|improve this answer

























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            you can create a function that returns the merged string validating when another string is smaller than the other and using a "merge identifier" which is going to be the special character to replace, something like this:



                            //----------------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;}


                            If one of the strings is smaller than the other, it will merge just the size of the smaller string but you could just add the missing characters by checking which string is longer and adding the characters from the merged string size to the end of the longer string.






                            share|improve this answer














                            you can create a function that returns the merged string validating when another string is smaller than the other and using a "merge identifier" which is going to be the special character to replace, something like this:



                            //----------------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;}


                            If one of the strings is smaller than the other, it will merge just the size of the smaller string but you could just add the missing characters by checking which string is longer and adding the characters from the merged string size to the end of the longer string.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 11 at 18:27

























                            answered Nov 11 at 18:22









                            Amaury Permer

                            279




                            279






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53250340%2fmerging-strings-together-in-c-not-adding-onto-merging%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Coverage of Google Street View

                                Full-time equivalent

                                Surfing