以下是将一长串数字分组用逗号隔开,每三个一组,转化为字符串.
例如:
2345678--->2,345,678
23--->23
private static String convert(long space) {
String str = String.valueOf(space);
StringBuilder builder = new StringBuilder(str);
str = builder.reverse().toString();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (i%3==0) {
//防越界&保留最高位
if (i+3>str.length()){
stringBuilder.append(str.substring(i));
break;
}
stringBuilder.append(str.substring(i, i + 3) + ",");
}
}
str = stringBuilder.reverse().toString();
//消除字符串长度为3的倍数时多出的','
if (str.charAt(0)==','){
str = str.substring(1);
}
return str;
}
还可以再继续优化,间隔,分隔符.....哎呀,肚子好疼,再见!
急着下班了,这个是简单的例子:结果为3位一输出,主要就是用了一个.substring方法,(z,z+3)就是获取z位到z+3位的数据,很简单。
public static void main(String[] args) {
String test = "abcdefghigk";
int z = 0;
for(int i=0;i
System.out.println(a);
z = z+3;
}
}
import java.util.*;
public class Test
{
public static void main(String args[])
{
System.out.println("pleast input a number:");
Scanner reader=new Scanner(System.in);
String inpt;
inpt=reader.next();
int inptLength = inpt.length();
int strLength;
boolean b = true;
if(inptLength%3 == 0)
{
strLength = inptLength/3;
}
else
{
b = false;
strLength = (int)inptLength/3 + 1;
}
String[] str = new String[strLength];
for(int i=0; i
if(b||(i!=str.length-1))
str[i] = inpt.substring(3*i,3*i+3);
else
str[i] = inpt.substring(3*i);
}
for(int i=0;i
System.out.print(str[i] + " ");
}
System.out.println();
}
}
这个程序可以运行,不过觉的自己写的不是很好,对JAVA提供的方法没有运用好,高手在来指点下吧.
//package com.color.program;
import java.util.ArrayList;
import java.util.List;
public class SubString {
public static List
List
for(;num.length()>3;){
list.add(num.substring(num.length()-3));
num = num.substring(0,num.length()-3);
}
if(num.length()>0){
list.add(num);
}
return list;
}
public static void main(String[] args){
String s = "1242332435234523464256245645634564356345634653423342134";
List
for(String str :l){
System.out.println(str);
}
}
}
----------result-----------------
134
342
423
653
634
345
356
564
634
645
245
256
464
523
234
435
332
242
1
public List
List
for (int i = 0; i < content.length(); i += 3) {
list.add(content.length() - i < 3 ? content.substring(i) : content.substring(i, i + 3));
}
return list;
}