简体   繁体   English

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

[英]Adding dot between two characters in java string

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?我怎样才能做到这一点?

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 replaceAll to do it on longer strings, like this:您还可以使用replaceAll在更长的字符串上执行此操作,如下所示:

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

This prints打印

1.9,2.8,3.7,4.6

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

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

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

this function can accepts all number and returns a dotted string, with small touches it can accepts many in other types of data an return data with options这个 function 可以接受所有数字并返回一个带点的字符串,稍加改动它可以接受许多其他类型的数据返回带有选项的数据

    fun getStringWithDot(nums: Int): String {
var str = ""
val istr = nums.toString()
for (ch in istr.indices){
    if (ch == istr.length-1){
        str += istr.substring(0,1)
    }else{
        str += istr.substring(ch,ch+1) + "."
    }

}
return str

} }

public static void main(String args[])

{
Scanner S=new Scanner(System.in);

int arr[];

int number;

number=S.nextInt();

int length=Integer.toString(number).length();

arr=new int[length];

char arr2[];

arr2=new char[length];

int count=0;

char arr3[];

arr3=new char[length];

String Q=Integer.toString(number);

for(int i=0;i<arr3.length;i++)

{

    System.out.print(Q.charAt(i)+".");

}

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM