How to add a hyphen between a line

I have the following sting xxxxx, I want to add a hyphen like x-xxxx, how to do it with Java?

+2


a source to share


6 answers


You can use String#substring()

.

String newstring = string.substring(0, 1) + "-" + string.substring(1);

      



You only need to check the length of the string beforehand to avoid IndexOutOfBoundsException

, but this is no more than obvious.

+13


a source


String

is an immutable type in Java, which means that you cannot change the sequence of characters that it represents after it has been constructed String

.

You can use an instance of the class StringBuilder

to create a new instance String

, which is some transformation of the original one String

. For example add a hyphen as you ask, you can do this:

String str = "xxxxx";
StringBuilder builder = new StringBuilder(str);
builder.insert(1, '-');
String hyphenated = builder.toString(); // "x-xxxx"

      

StringBuilder

initially contains a copy of the content str

; that is "xxxxx"

.

The call insert

changes the content of the builder to "x-xxxx"

.

The call toString

returns a new String

one containing a copy of the contents of the string builder.



Since the type is String

immutable, no amount of content manipulation StringBuilder

will ever change the content str

or hyphenated

.

You can change what String

instance means by str

doing

str = builder.toString();

      

instead

String hyphenated = builder.toString();

      

But it never has the content of the line that is str

related to the modified one, because that is not possible. Instead, it is str

used to refer to the containing instance "xxxxx"

and now refers to the containing instance "x-xxxx"

.

+4


a source


Assuming

String in = "ABCDEF";
String out;

      

Then any of :

out = in.replaceFirst(".", "$0-");

      

or

out = String.format("%1$s-%2$s", in.substring(0,1), in.substring(1));

      

or

out = in.substring(0,1) + "-" + in.substring(1);

      

or

out = new StringBuilder(in).insert(1, '-').toString();

      

will do out = "A-BCDEF"

.

+4


a source


String xxx = "xxxxx";
String hyphened = xxx.substring(0,1) + "-" + xxx.substring(1);

      

+1


a source


You can do:

String orgStr = "xxxxx";
String newStr = orgStr.substring(0,1) + "-" + orgStr.substring(1)

      

+1


a source


Here's another way:

MaskFormatter fmt = new MaskFormatter("*-****");
fmt.setValueContainsLiteralCharacters(false);
System.out.println(fmt.valueToString("12345"));

      

0


a source







All Articles