Printing string with edited character using char array instead of creating new String object

The purpose of this code is to change the line "Happy" to "A Hippy".

String originalStr = "A Happy";
char[] charOriStr = originalStr.toCharArray();
charOriStr[3] = 'i'; //simplified code, we are supposed to loop through the String

      

To print the corrected line, I use:

System.out.println(charOriStr);

      

However, the recommended solution looks like this:

String revised = new String(charOriStr);
System.out.println(revised);

      

I'm a newbie and I'm not sure if I should follow the recommended solution as a best practice guideline? Please rate some recommendations on this, thanks.

+3


source to share


3 answers


Whom they recommend this way is clearly not the case here. Since you already have a char array in your hand, you don't need to convert it to String again, just for printing. Since the method println

you are using will convert your string to char array again.



+3


source


You can use StringBuffer

or StringBuilder

and edit the same input instead of creating a new one.

public class HelloWorld
{
    public static void main(String[] args)
    {
        StringBuilder str = new StringBuilder("A Happy");
        str.setCharAt(3,'i');
        System.out.println(str);
    }
}

      



Bottomline - Check out StringBuilder, there are many cool things you can do with it.

+2


source


A char[]

is an implementation prior to java 8. For a String that can contain Unicode text for all scripts in the world, Latin, Arabic, Greek, Cyrillic, etc.

Keeping the String abstraction layer more ... abstract and definitely completely complete. If you are looking to replace a coil in your car, you do not expect to receive it back as a kit.

For example, char

is a 2-byte value for UTF-16 encoding, a form of Unicode. Currently, the values int

, so-called code points, have fewer irregularities. So you could make a code point based solution and handled Chinese with that too.

+2


source







All Articles