java 在java字符串中的两个字符之间添加点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11785756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:20:52  来源:igfitidea点击:

Adding dot between two characters in java string

javastringreplace

提问by user1486269

I have a string:

我有一个字符串:

String x = "10";

Now I want to add .between the numbers and print it like this

现在我想.在数字之间添加并像这样打印

1.0

How can I achieve this?

我怎样才能做到这一点?

回答by dasblinkenlight

You can split the string into the first character and the rest of the string, and then insert a dot '.'in between, like this:

您可以将字符串拆分为第一个字符和字符串的其余部分,然后'.'在中间插入一个点,如下所示:

String res = x.substring(0,1)+"."+x.substring(1);
//           ^^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^
//            the first digit     the rest of the string

You can also use replaceAllto do it on longer strings, like this:

您还可以使用replaceAll在更长的字符串上执行此操作,如下所示:

String orig = "19,28,37,46";
System.out.println(orig.replaceAll("(\d)(\d)", "."));

This prints

打印

1.9,2.8,3.7,4.6

回答by user1329572

Use the DecimalFormatclass to better decouple the value and its representation.

使用DecimalFormat该类可以更好地解耦值及其表示。

回答by kgautron

If the String is always a 2-digit number :

如果字符串始终是 2 位数字:

String result = x.charAt(0) + "." + x.charAt(1);