String replace() returns extra space in Java

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
16
down vote

favorite
2












Consider:



System.out.println(new String(new char[10]).replace("", "hello"));


has output:



hellohellohellohellohellohellohellohellohellohello 


but:



System.out.println(new String(new char[10]).replace("", "hello")); 


has output:



hello hello hello hello hello hello hello hello hello hello


Where are these extra spaces coming from?







share|improve this question






















  • You should loop through the string and print each character.
    – copper.hat
    Aug 18 at 22:56






  • 1




    @Ferrybig There was never a trailing space. The OP's original description was (presumably) incorrect. See for example ideone.com/492Cml.
    – Radiodef
    Aug 19 at 2:43














up vote
16
down vote

favorite
2












Consider:



System.out.println(new String(new char[10]).replace("", "hello"));


has output:



hellohellohellohellohellohellohellohellohellohello 


but:



System.out.println(new String(new char[10]).replace("", "hello")); 


has output:



hello hello hello hello hello hello hello hello hello hello


Where are these extra spaces coming from?







share|improve this question






















  • You should loop through the string and print each character.
    – copper.hat
    Aug 18 at 22:56






  • 1




    @Ferrybig There was never a trailing space. The OP's original description was (presumably) incorrect. See for example ideone.com/492Cml.
    – Radiodef
    Aug 19 at 2:43












up vote
16
down vote

favorite
2









up vote
16
down vote

favorite
2






2





Consider:



System.out.println(new String(new char[10]).replace("", "hello"));


has output:



hellohellohellohellohellohellohellohellohellohello 


but:



System.out.println(new String(new char[10]).replace("", "hello")); 


has output:



hello hello hello hello hello hello hello hello hello hello


Where are these extra spaces coming from?







share|improve this question














Consider:



System.out.println(new String(new char[10]).replace("", "hello"));


has output:



hellohellohellohellohellohellohellohellohellohello 


but:



System.out.println(new String(new char[10]).replace("", "hello")); 


has output:



hello hello hello hello hello hello hello hello hello hello


Where are these extra spaces coming from?









share|improve this question













share|improve this question




share|improve this question








edited Aug 20 at 10:15









Sun

13.1k31541




13.1k31541










asked Aug 18 at 16:02









Ansh

964




964











  • You should loop through the string and print each character.
    – copper.hat
    Aug 18 at 22:56






  • 1




    @Ferrybig There was never a trailing space. The OP's original description was (presumably) incorrect. See for example ideone.com/492Cml.
    – Radiodef
    Aug 19 at 2:43
















  • You should loop through the string and print each character.
    – copper.hat
    Aug 18 at 22:56






  • 1




    @Ferrybig There was never a trailing space. The OP's original description was (presumably) incorrect. See for example ideone.com/492Cml.
    – Radiodef
    Aug 19 at 2:43















You should loop through the string and print each character.
– copper.hat
Aug 18 at 22:56




You should loop through the string and print each character.
– copper.hat
Aug 18 at 22:56




1




1




@Ferrybig There was never a trailing space. The OP's original description was (presumably) incorrect. See for example ideone.com/492Cml.
– Radiodef
Aug 19 at 2:43




@Ferrybig There was never a trailing space. The OP's original description was (presumably) incorrect. See for example ideone.com/492Cml.
– Radiodef
Aug 19 at 2:43












4 Answers
4






active

oldest

votes

















up vote
14
down vote













It is not a space. It is how your IDE/console shows character which new char[10] is filled with by default.



You are not replacing with anything, so it stays in string. Instead with .replace("", "hello") you are replacing only empty string "". Important thing is that Java assumes that "" exists at:



  • start of the string,

  • end of string,

  • and between each of the characters

since we can get "abc" with:



"abc" = "" + "a" + "" + "b" + "" + "c" + ""`;
//^ ^ ^ ^


Now .replace("", "hello") replaces each of those "" with "hello", so for string of length 10 it will place additional 11 hellos (not 10), without modifying , which will be shown at your output like spaces.




Maybe this will be easier to grasp:



System.out.println("aaa".replace("", "X"));


  • lets represent each "" with as |. We will get "|a|a|a|" (notice that there are 4 |)

  • so replacing "" with X will result in "XaXaXaX" (but in your case instead of a your console will print using character which will look like space)





share|improve this answer





























    up vote
    11
    down vote













    Short version



    represents character NUL, it does not equals empty string "".



    Long version




    1. When you try to create a String with empty char[10],:



      String input = new String(new char[10]);


      this String will contains 10 NUL character:



      |NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|



    2. When you call input.replace("", "hello"), the NUL value() will be replaced by hello:



      |hello|hello|hello|hello|hello|hello|hello|hello|hello|hello|



    3. When you call input.replace("", "hello"), the NUL value will not be replaced since it does not match empty string "":



      |hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|






    share|improve this answer





























      up vote
      7
      down vote













      Explanation



      You are using the method String#replace(CharSequence target, CharSequence replacement) (documentation).



      If invoked with an empty target character sequence replace("", replacement) it will not replace the elements in the source, but insert the replacement before every character.



      This is because "" matches the positions between the characters, not the characters themselves. So every position between will be replaced, i.e. replacement is inserted.



      Example:



      "abc".replace("", "d") // Results in "dadbdcd"


      Your string contains only the default value of char at every position, it is






      using the method thus results in:



      hellohellohellohellohellohellohellohellohellohello



      Display



      Your console probably displayed the character as whitespace, while it's actually not a whitespace but .



      If I try out your code in a different console, I get:



      enter image description here



      Confirming that the characters are indeed not spaces but something different (i.e. ).






      share|improve this answer






















      • replace("", ...) inserts the replacement at the end of the string too. See e.g. ideone.com/492Cml.
        – Radiodef
        Aug 19 at 2:45


















      up vote
      3
      down vote













      char's default value is u0000 which can also be represented as . So your new char[10] contains 10 s.



      In the first statement you clearly replace with "hello". But in the second statement you leave out the default value. Which your IDE output chooses to show as a space.






      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: false,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        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%2f51910381%2fstring-replace-returns-extra-space-in-java%23new-answer', 'question_page');

        );

        Post as a guest






























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        14
        down vote













        It is not a space. It is how your IDE/console shows character which new char[10] is filled with by default.



        You are not replacing with anything, so it stays in string. Instead with .replace("", "hello") you are replacing only empty string "". Important thing is that Java assumes that "" exists at:



        • start of the string,

        • end of string,

        • and between each of the characters

        since we can get "abc" with:



        "abc" = "" + "a" + "" + "b" + "" + "c" + ""`;
        //^ ^ ^ ^


        Now .replace("", "hello") replaces each of those "" with "hello", so for string of length 10 it will place additional 11 hellos (not 10), without modifying , which will be shown at your output like spaces.




        Maybe this will be easier to grasp:



        System.out.println("aaa".replace("", "X"));


        • lets represent each "" with as |. We will get "|a|a|a|" (notice that there are 4 |)

        • so replacing "" with X will result in "XaXaXaX" (but in your case instead of a your console will print using character which will look like space)





        share|improve this answer


























          up vote
          14
          down vote













          It is not a space. It is how your IDE/console shows character which new char[10] is filled with by default.



          You are not replacing with anything, so it stays in string. Instead with .replace("", "hello") you are replacing only empty string "". Important thing is that Java assumes that "" exists at:



          • start of the string,

          • end of string,

          • and between each of the characters

          since we can get "abc" with:



          "abc" = "" + "a" + "" + "b" + "" + "c" + ""`;
          //^ ^ ^ ^


          Now .replace("", "hello") replaces each of those "" with "hello", so for string of length 10 it will place additional 11 hellos (not 10), without modifying , which will be shown at your output like spaces.




          Maybe this will be easier to grasp:



          System.out.println("aaa".replace("", "X"));


          • lets represent each "" with as |. We will get "|a|a|a|" (notice that there are 4 |)

          • so replacing "" with X will result in "XaXaXaX" (but in your case instead of a your console will print using character which will look like space)





          share|improve this answer
























            up vote
            14
            down vote










            up vote
            14
            down vote









            It is not a space. It is how your IDE/console shows character which new char[10] is filled with by default.



            You are not replacing with anything, so it stays in string. Instead with .replace("", "hello") you are replacing only empty string "". Important thing is that Java assumes that "" exists at:



            • start of the string,

            • end of string,

            • and between each of the characters

            since we can get "abc" with:



            "abc" = "" + "a" + "" + "b" + "" + "c" + ""`;
            //^ ^ ^ ^


            Now .replace("", "hello") replaces each of those "" with "hello", so for string of length 10 it will place additional 11 hellos (not 10), without modifying , which will be shown at your output like spaces.




            Maybe this will be easier to grasp:



            System.out.println("aaa".replace("", "X"));


            • lets represent each "" with as |. We will get "|a|a|a|" (notice that there are 4 |)

            • so replacing "" with X will result in "XaXaXaX" (but in your case instead of a your console will print using character which will look like space)





            share|improve this answer














            It is not a space. It is how your IDE/console shows character which new char[10] is filled with by default.



            You are not replacing with anything, so it stays in string. Instead with .replace("", "hello") you are replacing only empty string "". Important thing is that Java assumes that "" exists at:



            • start of the string,

            • end of string,

            • and between each of the characters

            since we can get "abc" with:



            "abc" = "" + "a" + "" + "b" + "" + "c" + ""`;
            //^ ^ ^ ^


            Now .replace("", "hello") replaces each of those "" with "hello", so for string of length 10 it will place additional 11 hellos (not 10), without modifying , which will be shown at your output like spaces.




            Maybe this will be easier to grasp:



            System.out.println("aaa".replace("", "X"));


            • lets represent each "" with as |. We will get "|a|a|a|" (notice that there are 4 |)

            • so replacing "" with X will result in "XaXaXaX" (but in your case instead of a your console will print using character which will look like space)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Aug 18 at 17:17

























            answered Aug 18 at 16:16









            Pshemo

            91.1k14127178




            91.1k14127178






















                up vote
                11
                down vote













                Short version



                represents character NUL, it does not equals empty string "".



                Long version




                1. When you try to create a String with empty char[10],:



                  String input = new String(new char[10]);


                  this String will contains 10 NUL character:



                  |NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|



                2. When you call input.replace("", "hello"), the NUL value() will be replaced by hello:



                  |hello|hello|hello|hello|hello|hello|hello|hello|hello|hello|



                3. When you call input.replace("", "hello"), the NUL value will not be replaced since it does not match empty string "":



                  |hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|






                share|improve this answer


























                  up vote
                  11
                  down vote













                  Short version



                  represents character NUL, it does not equals empty string "".



                  Long version




                  1. When you try to create a String with empty char[10],:



                    String input = new String(new char[10]);


                    this String will contains 10 NUL character:



                    |NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|



                  2. When you call input.replace("", "hello"), the NUL value() will be replaced by hello:



                    |hello|hello|hello|hello|hello|hello|hello|hello|hello|hello|



                  3. When you call input.replace("", "hello"), the NUL value will not be replaced since it does not match empty string "":



                    |hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|






                  share|improve this answer
























                    up vote
                    11
                    down vote










                    up vote
                    11
                    down vote









                    Short version



                    represents character NUL, it does not equals empty string "".



                    Long version




                    1. When you try to create a String with empty char[10],:



                      String input = new String(new char[10]);


                      this String will contains 10 NUL character:



                      |NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|



                    2. When you call input.replace("", "hello"), the NUL value() will be replaced by hello:



                      |hello|hello|hello|hello|hello|hello|hello|hello|hello|hello|



                    3. When you call input.replace("", "hello"), the NUL value will not be replaced since it does not match empty string "":



                      |hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|






                    share|improve this answer














                    Short version



                    represents character NUL, it does not equals empty string "".



                    Long version




                    1. When you try to create a String with empty char[10],:



                      String input = new String(new char[10]);


                      this String will contains 10 NUL character:



                      |NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|NUL|



                    2. When you call input.replace("", "hello"), the NUL value() will be replaced by hello:



                      |hello|hello|hello|hello|hello|hello|hello|hello|hello|hello|



                    3. When you call input.replace("", "hello"), the NUL value will not be replaced since it does not match empty string "":



                      |hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|NUL|hello|







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Aug 18 at 19:15

























                    answered Aug 18 at 16:19









                    Sun

                    13.1k31541




                    13.1k31541




















                        up vote
                        7
                        down vote













                        Explanation



                        You are using the method String#replace(CharSequence target, CharSequence replacement) (documentation).



                        If invoked with an empty target character sequence replace("", replacement) it will not replace the elements in the source, but insert the replacement before every character.



                        This is because "" matches the positions between the characters, not the characters themselves. So every position between will be replaced, i.e. replacement is inserted.



                        Example:



                        "abc".replace("", "d") // Results in "dadbdcd"


                        Your string contains only the default value of char at every position, it is






                        using the method thus results in:



                        hellohellohellohellohellohellohellohellohellohello



                        Display



                        Your console probably displayed the character as whitespace, while it's actually not a whitespace but .



                        If I try out your code in a different console, I get:



                        enter image description here



                        Confirming that the characters are indeed not spaces but something different (i.e. ).






                        share|improve this answer






















                        • replace("", ...) inserts the replacement at the end of the string too. See e.g. ideone.com/492Cml.
                          – Radiodef
                          Aug 19 at 2:45















                        up vote
                        7
                        down vote













                        Explanation



                        You are using the method String#replace(CharSequence target, CharSequence replacement) (documentation).



                        If invoked with an empty target character sequence replace("", replacement) it will not replace the elements in the source, but insert the replacement before every character.



                        This is because "" matches the positions between the characters, not the characters themselves. So every position between will be replaced, i.e. replacement is inserted.



                        Example:



                        "abc".replace("", "d") // Results in "dadbdcd"


                        Your string contains only the default value of char at every position, it is






                        using the method thus results in:



                        hellohellohellohellohellohellohellohellohellohello



                        Display



                        Your console probably displayed the character as whitespace, while it's actually not a whitespace but .



                        If I try out your code in a different console, I get:



                        enter image description here



                        Confirming that the characters are indeed not spaces but something different (i.e. ).






                        share|improve this answer






















                        • replace("", ...) inserts the replacement at the end of the string too. See e.g. ideone.com/492Cml.
                          – Radiodef
                          Aug 19 at 2:45













                        up vote
                        7
                        down vote










                        up vote
                        7
                        down vote









                        Explanation



                        You are using the method String#replace(CharSequence target, CharSequence replacement) (documentation).



                        If invoked with an empty target character sequence replace("", replacement) it will not replace the elements in the source, but insert the replacement before every character.



                        This is because "" matches the positions between the characters, not the characters themselves. So every position between will be replaced, i.e. replacement is inserted.



                        Example:



                        "abc".replace("", "d") // Results in "dadbdcd"


                        Your string contains only the default value of char at every position, it is






                        using the method thus results in:



                        hellohellohellohellohellohellohellohellohellohello



                        Display



                        Your console probably displayed the character as whitespace, while it's actually not a whitespace but .



                        If I try out your code in a different console, I get:



                        enter image description here



                        Confirming that the characters are indeed not spaces but something different (i.e. ).






                        share|improve this answer














                        Explanation



                        You are using the method String#replace(CharSequence target, CharSequence replacement) (documentation).



                        If invoked with an empty target character sequence replace("", replacement) it will not replace the elements in the source, but insert the replacement before every character.



                        This is because "" matches the positions between the characters, not the characters themselves. So every position between will be replaced, i.e. replacement is inserted.



                        Example:



                        "abc".replace("", "d") // Results in "dadbdcd"


                        Your string contains only the default value of char at every position, it is






                        using the method thus results in:



                        hellohellohellohellohellohellohellohellohellohello



                        Display



                        Your console probably displayed the character as whitespace, while it's actually not a whitespace but .



                        If I try out your code in a different console, I get:



                        enter image description here



                        Confirming that the characters are indeed not spaces but something different (i.e. ).







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Aug 18 at 16:21

























                        answered Aug 18 at 16:15









                        Zabuza

                        10.6k52538




                        10.6k52538











                        • replace("", ...) inserts the replacement at the end of the string too. See e.g. ideone.com/492Cml.
                          – Radiodef
                          Aug 19 at 2:45

















                        • replace("", ...) inserts the replacement at the end of the string too. See e.g. ideone.com/492Cml.
                          – Radiodef
                          Aug 19 at 2:45
















                        replace("", ...) inserts the replacement at the end of the string too. See e.g. ideone.com/492Cml.
                        – Radiodef
                        Aug 19 at 2:45





                        replace("", ...) inserts the replacement at the end of the string too. See e.g. ideone.com/492Cml.
                        – Radiodef
                        Aug 19 at 2:45











                        up vote
                        3
                        down vote













                        char's default value is u0000 which can also be represented as . So your new char[10] contains 10 s.



                        In the first statement you clearly replace with "hello". But in the second statement you leave out the default value. Which your IDE output chooses to show as a space.






                        share|improve this answer
























                          up vote
                          3
                          down vote













                          char's default value is u0000 which can also be represented as . So your new char[10] contains 10 s.



                          In the first statement you clearly replace with "hello". But in the second statement you leave out the default value. Which your IDE output chooses to show as a space.






                          share|improve this answer






















                            up vote
                            3
                            down vote










                            up vote
                            3
                            down vote









                            char's default value is u0000 which can also be represented as . So your new char[10] contains 10 s.



                            In the first statement you clearly replace with "hello". But in the second statement you leave out the default value. Which your IDE output chooses to show as a space.






                            share|improve this answer












                            char's default value is u0000 which can also be represented as . So your new char[10] contains 10 s.



                            In the first statement you clearly replace with "hello". But in the second statement you leave out the default value. Which your IDE output chooses to show as a space.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Aug 18 at 16:28









                            Roshana Pitigala

                            3,57162342




                            3,57162342



























                                 

                                draft saved


                                draft discarded















































                                 


                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f51910381%2fstring-replace-returns-extra-space-in-java%23new-answer', 'question_page');

                                );

                                Post as a guest













































































                                Comments

                                Popular posts from this blog

                                What does second last employer means? [closed]

                                Installing NextGIS Connect into QGIS 3?

                                One-line joke