How to add a hyphen between a line
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.
a source to share
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"
.
a source to share
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"
.
a source to share