Insert a character into a string









up vote
0
down vote

favorite












I need to insert a character into a string at every instance of that character. For example if my string was, "This is a test" and my character was 's' then my output would need to look like this: "Thiss iss a tesst"



any idea why this isn't working? Here's what I have so far. I am not supposed to add any extra preprocessor instructions or anything, just using what's here I need to figure this out.



#include <iostream>
#include <string>
using namespace std;

int main(){

string userString;
char userChar;

cin >> userString;
cin >> userChar;

for (int i = 0; i < userString.size(); i++)
if(userString.at(i) == userChar)
userString.insert(userString.begin() + i, userChar);


cout << userString;

return 0;


Update:



Here's the solution I worked out.



#include <iostream>
#include <string>
using namespace std;

int main()

string userString;
char userChar;
cout << "enter a string" << endl;
getline(cin, userString);
cout << "enter a character" << endl;
cin >> userChar;

for (int i = userString.size()-1; i >= 0; i--)
if(userString.at(i) == userChar)
userString.insert(userString.begin() + i, userChar);


cout << userString;
return 0;










share|improve this question























  • Consider: Once you find a match and insert a letter, what's the next letter your loop is going to look at?
    – 1201ProgramAlarm
    Nov 9 at 22:15






  • 2




    Consider this reasoning: "This is a test" has an 's' at index 3, so a new 's' is inserted there. "Thiss is a test" has an 's' at index 4, so a new 's' is inserted there. "Thisss is a test" has an 's' at index 5, so a new 's' is inserted there. "Thissss is a test" has an 's' at index 6, so a new 's' is inserted there. And on and on and on....
    – alter igel
    Nov 9 at 22:16











  • Recommend placing answers in an answer and not in the question.
    – user4581301
    Nov 9 at 22:38














up vote
0
down vote

favorite












I need to insert a character into a string at every instance of that character. For example if my string was, "This is a test" and my character was 's' then my output would need to look like this: "Thiss iss a tesst"



any idea why this isn't working? Here's what I have so far. I am not supposed to add any extra preprocessor instructions or anything, just using what's here I need to figure this out.



#include <iostream>
#include <string>
using namespace std;

int main(){

string userString;
char userChar;

cin >> userString;
cin >> userChar;

for (int i = 0; i < userString.size(); i++)
if(userString.at(i) == userChar)
userString.insert(userString.begin() + i, userChar);


cout << userString;

return 0;


Update:



Here's the solution I worked out.



#include <iostream>
#include <string>
using namespace std;

int main()

string userString;
char userChar;
cout << "enter a string" << endl;
getline(cin, userString);
cout << "enter a character" << endl;
cin >> userChar;

for (int i = userString.size()-1; i >= 0; i--)
if(userString.at(i) == userChar)
userString.insert(userString.begin() + i, userChar);


cout << userString;
return 0;










share|improve this question























  • Consider: Once you find a match and insert a letter, what's the next letter your loop is going to look at?
    – 1201ProgramAlarm
    Nov 9 at 22:15






  • 2




    Consider this reasoning: "This is a test" has an 's' at index 3, so a new 's' is inserted there. "Thiss is a test" has an 's' at index 4, so a new 's' is inserted there. "Thisss is a test" has an 's' at index 5, so a new 's' is inserted there. "Thissss is a test" has an 's' at index 6, so a new 's' is inserted there. And on and on and on....
    – alter igel
    Nov 9 at 22:16











  • Recommend placing answers in an answer and not in the question.
    – user4581301
    Nov 9 at 22:38












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I need to insert a character into a string at every instance of that character. For example if my string was, "This is a test" and my character was 's' then my output would need to look like this: "Thiss iss a tesst"



any idea why this isn't working? Here's what I have so far. I am not supposed to add any extra preprocessor instructions or anything, just using what's here I need to figure this out.



#include <iostream>
#include <string>
using namespace std;

int main(){

string userString;
char userChar;

cin >> userString;
cin >> userChar;

for (int i = 0; i < userString.size(); i++)
if(userString.at(i) == userChar)
userString.insert(userString.begin() + i, userChar);


cout << userString;

return 0;


Update:



Here's the solution I worked out.



#include <iostream>
#include <string>
using namespace std;

int main()

string userString;
char userChar;
cout << "enter a string" << endl;
getline(cin, userString);
cout << "enter a character" << endl;
cin >> userChar;

for (int i = userString.size()-1; i >= 0; i--)
if(userString.at(i) == userChar)
userString.insert(userString.begin() + i, userChar);


cout << userString;
return 0;










share|improve this question















I need to insert a character into a string at every instance of that character. For example if my string was, "This is a test" and my character was 's' then my output would need to look like this: "Thiss iss a tesst"



any idea why this isn't working? Here's what I have so far. I am not supposed to add any extra preprocessor instructions or anything, just using what's here I need to figure this out.



#include <iostream>
#include <string>
using namespace std;

int main(){

string userString;
char userChar;

cin >> userString;
cin >> userChar;

for (int i = 0; i < userString.size(); i++)
if(userString.at(i) == userChar)
userString.insert(userString.begin() + i, userChar);


cout << userString;

return 0;


Update:



Here's the solution I worked out.



#include <iostream>
#include <string>
using namespace std;

int main()

string userString;
char userChar;
cout << "enter a string" << endl;
getline(cin, userString);
cout << "enter a character" << endl;
cin >> userChar;

for (int i = userString.size()-1; i >= 0; i--)
if(userString.at(i) == userChar)
userString.insert(userString.begin() + i, userChar);


cout << userString;
return 0;







c++ string insert character






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 9 at 22:26

























asked Nov 9 at 22:13









Parker Mecham

42




42











  • Consider: Once you find a match and insert a letter, what's the next letter your loop is going to look at?
    – 1201ProgramAlarm
    Nov 9 at 22:15






  • 2




    Consider this reasoning: "This is a test" has an 's' at index 3, so a new 's' is inserted there. "Thiss is a test" has an 's' at index 4, so a new 's' is inserted there. "Thisss is a test" has an 's' at index 5, so a new 's' is inserted there. "Thissss is a test" has an 's' at index 6, so a new 's' is inserted there. And on and on and on....
    – alter igel
    Nov 9 at 22:16











  • Recommend placing answers in an answer and not in the question.
    – user4581301
    Nov 9 at 22:38
















  • Consider: Once you find a match and insert a letter, what's the next letter your loop is going to look at?
    – 1201ProgramAlarm
    Nov 9 at 22:15






  • 2




    Consider this reasoning: "This is a test" has an 's' at index 3, so a new 's' is inserted there. "Thiss is a test" has an 's' at index 4, so a new 's' is inserted there. "Thisss is a test" has an 's' at index 5, so a new 's' is inserted there. "Thissss is a test" has an 's' at index 6, so a new 's' is inserted there. And on and on and on....
    – alter igel
    Nov 9 at 22:16











  • Recommend placing answers in an answer and not in the question.
    – user4581301
    Nov 9 at 22:38















Consider: Once you find a match and insert a letter, what's the next letter your loop is going to look at?
– 1201ProgramAlarm
Nov 9 at 22:15




Consider: Once you find a match and insert a letter, what's the next letter your loop is going to look at?
– 1201ProgramAlarm
Nov 9 at 22:15




2




2




Consider this reasoning: "This is a test" has an 's' at index 3, so a new 's' is inserted there. "Thiss is a test" has an 's' at index 4, so a new 's' is inserted there. "Thisss is a test" has an 's' at index 5, so a new 's' is inserted there. "Thissss is a test" has an 's' at index 6, so a new 's' is inserted there. And on and on and on....
– alter igel
Nov 9 at 22:16





Consider this reasoning: "This is a test" has an 's' at index 3, so a new 's' is inserted there. "Thiss is a test" has an 's' at index 4, so a new 's' is inserted there. "Thisss is a test" has an 's' at index 5, so a new 's' is inserted there. "Thissss is a test" has an 's' at index 6, so a new 's' is inserted there. And on and on and on....
– alter igel
Nov 9 at 22:16













Recommend placing answers in an answer and not in the question.
– user4581301
Nov 9 at 22:38




Recommend placing answers in an answer and not in the question.
– user4581301
Nov 9 at 22:38












2 Answers
2






active

oldest

votes

















up vote
0
down vote













I don't know why you want to go through the string backwards. Anyway. Your problem is that once you insert a character at some position, your loop will encounter the inserted character again in the next iteration and insert another. Ad infinitum.



#include <cstddef> // std::size_t, the correct type for indexes and sizes of objects in mem
#include <string>
#include <iostream>

int main()

std::cout << "Enter a string: ";
std::string userString; // define variables as close
std::getline(std::cin, userString);

std::cout << "Enter a character: ";
char userChar; // to where they're used as possible
std::cin >> userChar;

for (std::size_t i; i < userString.size(); ++i)
if (userString[i] == userChar) // no need to use std::string::at() 1)
userString.insert(userString.begin() + i, userChar);
++i; // advance the index to not read the same character again.



std::cout << userString << 'n';



1) since it is allready sure that the index will be in a valid range.






share|improve this answer



























    up vote
    0
    down vote













    Your first solution probably ends up looping infinitely if you ever find one of the chosen character because you always insert one more copy ahead and keeps finding the same char ever after.



    std::basic_string has a find function. It's always better to use code offered by a library than self made code. Here's my proposed solution:



    std::string& duplicate_char(std::string& str, char val)

    using std::string;

    auto pos = str.find(val); // finds first index of character val or npos if unsuccessful
    while (pos != string::npos)

    str.insert(pos, 1, val); // insert at pos one character val
    pos = str.find(val, pos + 2); // find the next occurence of val starting after the newly inserted character


    return str;



    You may use this function like this:



    int main()

    std::string testStr"Thiss iss a tesst";
    duplicate_char(testStr, 's');

    std::cout << testStr << std::endl;






    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%2f53233929%2finsert-a-character-into-a-string%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote













      I don't know why you want to go through the string backwards. Anyway. Your problem is that once you insert a character at some position, your loop will encounter the inserted character again in the next iteration and insert another. Ad infinitum.



      #include <cstddef> // std::size_t, the correct type for indexes and sizes of objects in mem
      #include <string>
      #include <iostream>

      int main()

      std::cout << "Enter a string: ";
      std::string userString; // define variables as close
      std::getline(std::cin, userString);

      std::cout << "Enter a character: ";
      char userChar; // to where they're used as possible
      std::cin >> userChar;

      for (std::size_t i; i < userString.size(); ++i)
      if (userString[i] == userChar) // no need to use std::string::at() 1)
      userString.insert(userString.begin() + i, userChar);
      ++i; // advance the index to not read the same character again.



      std::cout << userString << 'n';



      1) since it is allready sure that the index will be in a valid range.






      share|improve this answer
























        up vote
        0
        down vote













        I don't know why you want to go through the string backwards. Anyway. Your problem is that once you insert a character at some position, your loop will encounter the inserted character again in the next iteration and insert another. Ad infinitum.



        #include <cstddef> // std::size_t, the correct type for indexes and sizes of objects in mem
        #include <string>
        #include <iostream>

        int main()

        std::cout << "Enter a string: ";
        std::string userString; // define variables as close
        std::getline(std::cin, userString);

        std::cout << "Enter a character: ";
        char userChar; // to where they're used as possible
        std::cin >> userChar;

        for (std::size_t i; i < userString.size(); ++i)
        if (userString[i] == userChar) // no need to use std::string::at() 1)
        userString.insert(userString.begin() + i, userChar);
        ++i; // advance the index to not read the same character again.



        std::cout << userString << 'n';



        1) since it is allready sure that the index will be in a valid range.






        share|improve this answer






















          up vote
          0
          down vote










          up vote
          0
          down vote









          I don't know why you want to go through the string backwards. Anyway. Your problem is that once you insert a character at some position, your loop will encounter the inserted character again in the next iteration and insert another. Ad infinitum.



          #include <cstddef> // std::size_t, the correct type for indexes and sizes of objects in mem
          #include <string>
          #include <iostream>

          int main()

          std::cout << "Enter a string: ";
          std::string userString; // define variables as close
          std::getline(std::cin, userString);

          std::cout << "Enter a character: ";
          char userChar; // to where they're used as possible
          std::cin >> userChar;

          for (std::size_t i; i < userString.size(); ++i)
          if (userString[i] == userChar) // no need to use std::string::at() 1)
          userString.insert(userString.begin() + i, userChar);
          ++i; // advance the index to not read the same character again.



          std::cout << userString << 'n';



          1) since it is allready sure that the index will be in a valid range.






          share|improve this answer












          I don't know why you want to go through the string backwards. Anyway. Your problem is that once you insert a character at some position, your loop will encounter the inserted character again in the next iteration and insert another. Ad infinitum.



          #include <cstddef> // std::size_t, the correct type for indexes and sizes of objects in mem
          #include <string>
          #include <iostream>

          int main()

          std::cout << "Enter a string: ";
          std::string userString; // define variables as close
          std::getline(std::cin, userString);

          std::cout << "Enter a character: ";
          char userChar; // to where they're used as possible
          std::cin >> userChar;

          for (std::size_t i; i < userString.size(); ++i)
          if (userString[i] == userChar) // no need to use std::string::at() 1)
          userString.insert(userString.begin() + i, userChar);
          ++i; // advance the index to not read the same character again.



          std::cout << userString << 'n';



          1) since it is allready sure that the index will be in a valid range.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 9 at 23:07









          Swordfish

          8,49511234




          8,49511234






















              up vote
              0
              down vote













              Your first solution probably ends up looping infinitely if you ever find one of the chosen character because you always insert one more copy ahead and keeps finding the same char ever after.



              std::basic_string has a find function. It's always better to use code offered by a library than self made code. Here's my proposed solution:



              std::string& duplicate_char(std::string& str, char val)

              using std::string;

              auto pos = str.find(val); // finds first index of character val or npos if unsuccessful
              while (pos != string::npos)

              str.insert(pos, 1, val); // insert at pos one character val
              pos = str.find(val, pos + 2); // find the next occurence of val starting after the newly inserted character


              return str;



              You may use this function like this:



              int main()

              std::string testStr"Thiss iss a tesst";
              duplicate_char(testStr, 's');

              std::cout << testStr << std::endl;






              share|improve this answer
























                up vote
                0
                down vote













                Your first solution probably ends up looping infinitely if you ever find one of the chosen character because you always insert one more copy ahead and keeps finding the same char ever after.



                std::basic_string has a find function. It's always better to use code offered by a library than self made code. Here's my proposed solution:



                std::string& duplicate_char(std::string& str, char val)

                using std::string;

                auto pos = str.find(val); // finds first index of character val or npos if unsuccessful
                while (pos != string::npos)

                str.insert(pos, 1, val); // insert at pos one character val
                pos = str.find(val, pos + 2); // find the next occurence of val starting after the newly inserted character


                return str;



                You may use this function like this:



                int main()

                std::string testStr"Thiss iss a tesst";
                duplicate_char(testStr, 's');

                std::cout << testStr << std::endl;






                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Your first solution probably ends up looping infinitely if you ever find one of the chosen character because you always insert one more copy ahead and keeps finding the same char ever after.



                  std::basic_string has a find function. It's always better to use code offered by a library than self made code. Here's my proposed solution:



                  std::string& duplicate_char(std::string& str, char val)

                  using std::string;

                  auto pos = str.find(val); // finds first index of character val or npos if unsuccessful
                  while (pos != string::npos)

                  str.insert(pos, 1, val); // insert at pos one character val
                  pos = str.find(val, pos + 2); // find the next occurence of val starting after the newly inserted character


                  return str;



                  You may use this function like this:



                  int main()

                  std::string testStr"Thiss iss a tesst";
                  duplicate_char(testStr, 's');

                  std::cout << testStr << std::endl;






                  share|improve this answer












                  Your first solution probably ends up looping infinitely if you ever find one of the chosen character because you always insert one more copy ahead and keeps finding the same char ever after.



                  std::basic_string has a find function. It's always better to use code offered by a library than self made code. Here's my proposed solution:



                  std::string& duplicate_char(std::string& str, char val)

                  using std::string;

                  auto pos = str.find(val); // finds first index of character val or npos if unsuccessful
                  while (pos != string::npos)

                  str.insert(pos, 1, val); // insert at pos one character val
                  pos = str.find(val, pos + 2); // find the next occurence of val starting after the newly inserted character


                  return str;



                  You may use this function like this:



                  int main()

                  std::string testStr"Thiss iss a tesst";
                  duplicate_char(testStr, 's');

                  std::cout << testStr << std::endl;







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 9 at 23:18









                  Julien Villemure-Fréchette

                  35017




                  35017



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53233929%2finsert-a-character-into-a-string%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

                      How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

                      Syphilis

                      Darth Vader #20