Remove null character embedded in string











up vote
0
down vote

favorite












I have a c++ string with embedded '' characters.



I have a function replaceAll() which should replace all occurrences of a pattern with another pattern. For "normal" strings it works fine. However, when I try to find the '' character my function does not work and I don't know why. replaceAll seems to be failing on string::find() which doesn't make sense to me.



// Replaces all occurrences of the text 'from' to the text 'to' in the specified input string.
// replaceAll("Foo123Foo", "Foo", "Bar"); // Bar123Bar
string replaceAll( string in, string from, string to )
{
string tmp = in;

if ( from.empty())
{
return in;
}

size_t start_pos = 0;

// tmp.find() fails to match on ""
while (( start_pos = tmp.find( from, start_pos )) != std::string::npos )
{
tmp.replace( start_pos, from.length(), to );
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}

return tmp;
}

int main(int argc, char* argv)
{
string stringWithNull = { '', '1', '', '2' };
printf("size=[%d] data=[%s]n", stringWithNull.size(), stringWithNull.c_str());

// This doesn't work in the special case of a null character and I don't know why
string replaced = replaceAll(stringWithNull, "", "");
printf("size=[%d] data=[%s]n", replaced.size(), replaced.c_str());
}


Output:



size=[4] data=
size=[4] data=









share|improve this question
























  • Did you debug it to see if your loop was really finding the character?
    – Matthieu Brucher
    Nov 7 at 15:48










  • BTW, you should actually search for the characters themselves, not strings.
    – Matthieu Brucher
    Nov 7 at 15:49










  • @MatthieuBrucher Why search for the characters? That limits the function. If I want to reaplce all occurances of ":)" from ":) :) :) :::too many smiles::: :) :) :)" that would be a real pain if I couldn't specify ":)" as the thing to replace.
    – NathanOliver
    Nov 7 at 16:05

















up vote
0
down vote

favorite












I have a c++ string with embedded '' characters.



I have a function replaceAll() which should replace all occurrences of a pattern with another pattern. For "normal" strings it works fine. However, when I try to find the '' character my function does not work and I don't know why. replaceAll seems to be failing on string::find() which doesn't make sense to me.



// Replaces all occurrences of the text 'from' to the text 'to' in the specified input string.
// replaceAll("Foo123Foo", "Foo", "Bar"); // Bar123Bar
string replaceAll( string in, string from, string to )
{
string tmp = in;

if ( from.empty())
{
return in;
}

size_t start_pos = 0;

// tmp.find() fails to match on ""
while (( start_pos = tmp.find( from, start_pos )) != std::string::npos )
{
tmp.replace( start_pos, from.length(), to );
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}

return tmp;
}

int main(int argc, char* argv)
{
string stringWithNull = { '', '1', '', '2' };
printf("size=[%d] data=[%s]n", stringWithNull.size(), stringWithNull.c_str());

// This doesn't work in the special case of a null character and I don't know why
string replaced = replaceAll(stringWithNull, "", "");
printf("size=[%d] data=[%s]n", replaced.size(), replaced.c_str());
}


Output:



size=[4] data=
size=[4] data=









share|improve this question
























  • Did you debug it to see if your loop was really finding the character?
    – Matthieu Brucher
    Nov 7 at 15:48










  • BTW, you should actually search for the characters themselves, not strings.
    – Matthieu Brucher
    Nov 7 at 15:49










  • @MatthieuBrucher Why search for the characters? That limits the function. If I want to reaplce all occurances of ":)" from ":) :) :) :::too many smiles::: :) :) :)" that would be a real pain if I couldn't specify ":)" as the thing to replace.
    – NathanOliver
    Nov 7 at 16:05















up vote
0
down vote

favorite









up vote
0
down vote

favorite











I have a c++ string with embedded '' characters.



I have a function replaceAll() which should replace all occurrences of a pattern with another pattern. For "normal" strings it works fine. However, when I try to find the '' character my function does not work and I don't know why. replaceAll seems to be failing on string::find() which doesn't make sense to me.



// Replaces all occurrences of the text 'from' to the text 'to' in the specified input string.
// replaceAll("Foo123Foo", "Foo", "Bar"); // Bar123Bar
string replaceAll( string in, string from, string to )
{
string tmp = in;

if ( from.empty())
{
return in;
}

size_t start_pos = 0;

// tmp.find() fails to match on ""
while (( start_pos = tmp.find( from, start_pos )) != std::string::npos )
{
tmp.replace( start_pos, from.length(), to );
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}

return tmp;
}

int main(int argc, char* argv)
{
string stringWithNull = { '', '1', '', '2' };
printf("size=[%d] data=[%s]n", stringWithNull.size(), stringWithNull.c_str());

// This doesn't work in the special case of a null character and I don't know why
string replaced = replaceAll(stringWithNull, "", "");
printf("size=[%d] data=[%s]n", replaced.size(), replaced.c_str());
}


Output:



size=[4] data=
size=[4] data=









share|improve this question















I have a c++ string with embedded '' characters.



I have a function replaceAll() which should replace all occurrences of a pattern with another pattern. For "normal" strings it works fine. However, when I try to find the '' character my function does not work and I don't know why. replaceAll seems to be failing on string::find() which doesn't make sense to me.



// Replaces all occurrences of the text 'from' to the text 'to' in the specified input string.
// replaceAll("Foo123Foo", "Foo", "Bar"); // Bar123Bar
string replaceAll( string in, string from, string to )
{
string tmp = in;

if ( from.empty())
{
return in;
}

size_t start_pos = 0;

// tmp.find() fails to match on ""
while (( start_pos = tmp.find( from, start_pos )) != std::string::npos )
{
tmp.replace( start_pos, from.length(), to );
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}

return tmp;
}

int main(int argc, char* argv)
{
string stringWithNull = { '', '1', '', '2' };
printf("size=[%d] data=[%s]n", stringWithNull.size(), stringWithNull.c_str());

// This doesn't work in the special case of a null character and I don't know why
string replaced = replaceAll(stringWithNull, "", "");
printf("size=[%d] data=[%s]n", replaced.size(), replaced.c_str());
}


Output:



size=[4] data=
size=[4] data=






c++ string null-character






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 7 at 15:58









NathanOliver

82.7k15112172




82.7k15112172










asked Nov 7 at 15:46









LeviX

1,68021833




1,68021833












  • Did you debug it to see if your loop was really finding the character?
    – Matthieu Brucher
    Nov 7 at 15:48










  • BTW, you should actually search for the characters themselves, not strings.
    – Matthieu Brucher
    Nov 7 at 15:49










  • @MatthieuBrucher Why search for the characters? That limits the function. If I want to reaplce all occurances of ":)" from ":) :) :) :::too many smiles::: :) :) :)" that would be a real pain if I couldn't specify ":)" as the thing to replace.
    – NathanOliver
    Nov 7 at 16:05




















  • Did you debug it to see if your loop was really finding the character?
    – Matthieu Brucher
    Nov 7 at 15:48










  • BTW, you should actually search for the characters themselves, not strings.
    – Matthieu Brucher
    Nov 7 at 15:49










  • @MatthieuBrucher Why search for the characters? That limits the function. If I want to reaplce all occurances of ":)" from ":) :) :) :::too many smiles::: :) :) :)" that would be a real pain if I couldn't specify ":)" as the thing to replace.
    – NathanOliver
    Nov 7 at 16:05


















Did you debug it to see if your loop was really finding the character?
– Matthieu Brucher
Nov 7 at 15:48




Did you debug it to see if your loop was really finding the character?
– Matthieu Brucher
Nov 7 at 15:48












BTW, you should actually search for the characters themselves, not strings.
– Matthieu Brucher
Nov 7 at 15:49




BTW, you should actually search for the characters themselves, not strings.
– Matthieu Brucher
Nov 7 at 15:49












@MatthieuBrucher Why search for the characters? That limits the function. If I want to reaplce all occurances of ":)" from ":) :) :) :::too many smiles::: :) :) :)" that would be a real pain if I couldn't specify ":)" as the thing to replace.
– NathanOliver
Nov 7 at 16:05






@MatthieuBrucher Why search for the characters? That limits the function. If I want to reaplce all occurances of ":)" from ":) :) :) :::too many smiles::: :) :) :)" that would be a real pain if I couldn't specify ":)" as the thing to replace.
– NathanOliver
Nov 7 at 16:05














2 Answers
2






active

oldest

votes

















up vote
5
down vote



accepted










The reason why it doesn't work in your case is that std::string constructor from const char* without size is going to read all elements up to, but not including nul-terminating char. As a result,



 replaceAll(stringWithNull, "", "");


Calls replaceAll with from set to empty string (replaceAll( string in, string from, string to )), which returns in unmodified.



To solve the problem, use a constructor which takes size, or initialize with list initialization, the same way you do it for your original string, for example:



replaceAll(stringWithNull, {''}, "");





share|improve this answer






























    up vote
    1
    down vote













    When you do



    replaceAll(stringWithNull, "", "");


    "" is the same as "" since std::string's constructor stops at the null character when being constructed from a c-string. That means you are searching for nothing and replacing it with nothing. What you need is



    string replaced = replaceAll(stringWithNull, {''}, "");


    to actually get from populated with a null character.






    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%2f53192898%2fremove-null-character-embedded-in-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
      5
      down vote



      accepted










      The reason why it doesn't work in your case is that std::string constructor from const char* without size is going to read all elements up to, but not including nul-terminating char. As a result,



       replaceAll(stringWithNull, "", "");


      Calls replaceAll with from set to empty string (replaceAll( string in, string from, string to )), which returns in unmodified.



      To solve the problem, use a constructor which takes size, or initialize with list initialization, the same way you do it for your original string, for example:



      replaceAll(stringWithNull, {''}, "");





      share|improve this answer



























        up vote
        5
        down vote



        accepted










        The reason why it doesn't work in your case is that std::string constructor from const char* without size is going to read all elements up to, but not including nul-terminating char. As a result,



         replaceAll(stringWithNull, "", "");


        Calls replaceAll with from set to empty string (replaceAll( string in, string from, string to )), which returns in unmodified.



        To solve the problem, use a constructor which takes size, or initialize with list initialization, the same way you do it for your original string, for example:



        replaceAll(stringWithNull, {''}, "");





        share|improve this answer

























          up vote
          5
          down vote



          accepted







          up vote
          5
          down vote



          accepted






          The reason why it doesn't work in your case is that std::string constructor from const char* without size is going to read all elements up to, but not including nul-terminating char. As a result,



           replaceAll(stringWithNull, "", "");


          Calls replaceAll with from set to empty string (replaceAll( string in, string from, string to )), which returns in unmodified.



          To solve the problem, use a constructor which takes size, or initialize with list initialization, the same way you do it for your original string, for example:



          replaceAll(stringWithNull, {''}, "");





          share|improve this answer














          The reason why it doesn't work in your case is that std::string constructor from const char* without size is going to read all elements up to, but not including nul-terminating char. As a result,



           replaceAll(stringWithNull, "", "");


          Calls replaceAll with from set to empty string (replaceAll( string in, string from, string to )), which returns in unmodified.



          To solve the problem, use a constructor which takes size, or initialize with list initialization, the same way you do it for your original string, for example:



          replaceAll(stringWithNull, {''}, "");






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 7 at 15:53

























          answered Nov 7 at 15:51









          SergeyA

          40.2k53781




          40.2k53781
























              up vote
              1
              down vote













              When you do



              replaceAll(stringWithNull, "", "");


              "" is the same as "" since std::string's constructor stops at the null character when being constructed from a c-string. That means you are searching for nothing and replacing it with nothing. What you need is



              string replaced = replaceAll(stringWithNull, {''}, "");


              to actually get from populated with a null character.






              share|improve this answer

























                up vote
                1
                down vote













                When you do



                replaceAll(stringWithNull, "", "");


                "" is the same as "" since std::string's constructor stops at the null character when being constructed from a c-string. That means you are searching for nothing and replacing it with nothing. What you need is



                string replaced = replaceAll(stringWithNull, {''}, "");


                to actually get from populated with a null character.






                share|improve this answer























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  When you do



                  replaceAll(stringWithNull, "", "");


                  "" is the same as "" since std::string's constructor stops at the null character when being constructed from a c-string. That means you are searching for nothing and replacing it with nothing. What you need is



                  string replaced = replaceAll(stringWithNull, {''}, "");


                  to actually get from populated with a null character.






                  share|improve this answer












                  When you do



                  replaceAll(stringWithNull, "", "");


                  "" is the same as "" since std::string's constructor stops at the null character when being constructed from a c-string. That means you are searching for nothing and replacing it with nothing. What you need is



                  string replaced = replaceAll(stringWithNull, {''}, "");


                  to actually get from populated with a null character.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 7 at 15:55









                  NathanOliver

                  82.7k15112172




                  82.7k15112172






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53192898%2fremove-null-character-embedded-in-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







                      這個網誌中的熱門文章

                      Tangent Lines Diagram Along Smooth Curve

                      Yusuf al-Mu'taman ibn Hud

                      Zucchini