开发者

how to add a hyphen in between a string

开发者 https://www.devze.com 2022-12-27 08:52 出处:网络
I have the following sting xxxxx, I want to add a hyphen like x-xxxx, how can I do so开发者_运维百科 using Java?You can make use of String#substring().

I have the following sting xxxxx, I want to add a hyphen like x-xxxx, how can I do so开发者_运维百科 using Java?


You can make use of String#substring().

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

You'll only need to check the string length beforehand to avoid IndexOutOfBoundsException, but that's nothing more than obvious.


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 make out = "A-BCDEF".


String is an immutable type in Java, meaning that you can't change the character sequence it represents once the String is constructed.

You can use an instance of the StringBuilder class to create a new instance of String that represents some transformation of the original 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"

The StringBuilder initially contains a copy of the contents of str; that is, "xxxxx".

The call to insert changes the builder's contents to "x-xxxx".

Calling toString returns a new String containing a copy the contents of the string builder.

Because the String type is immutable, no manipulation of the StringBuilder's contents will ever change the contents of str or hyphenated.

You can change what String instance str refers to by doing

str = builder.toString();

instead of

String hyphenated = builder.toString();

But never has the contents of a string that str refers to changed, because this is not possible. Instead, str used to refer to a instance containing "xxxxx", and now refers to a instance containing "x-xxxx".


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


You can do:

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


Here's another way:

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

精彩评论

暂无评论...
验证码 换一张
取 消