日期:2014-05-20  浏览次数:20758 次

JAVA格式化字符串
String   str   =   "05b101279acd0A ";  

怎么格式化为:  

05,b10,127,9ac,d0A  

请好心人帮助,在线等~

------解决方案--------------------
楼主,你是怎么格式化的了,依据是什么啊?

位数固定的就用substring
------解决方案--------------------
String str = "05b101279acd0A ";

str值是变值,是数字和字母的组合,长度也不固定.
------解决方案--------------------
因为我需要的是三位append一个逗号
========================
昏。这你也好意思问。。。。

直接用string进行操作
------解决方案--------------------
printf

------解决方案--------------------
你可以先把字符串倒过来,然后每三位分开一次,执行完成之后,在把字符串转过来。
不知道我的理解是不是您说的东西。
------解决方案--------------------
DecimalFormat decimalFormat = new DecimalFormat( "#,###,### ");
decimalFormat.format(i);

------解决方案--------------------
/**
*
*/
String getFormatString(String src, int n, String app)
{
if(src==null || n <1 || app==null || app.equals( " "))
return src;
String temp = src;
if(temp.length() <= n)
return temp;
return getFormatString(temp.substring(0,temp.length()-n),n,app)+app+temp.substring(temp.length()-n,temp.length());
}

System.out.println(getFormatString( "123s123%jahfd129 ",3, ", "));
------解决方案--------------------
给你写了个最容易看明白的方法,就是效率低些
String str = "05b101279acd0A ";
String rs = " ";
String ss = " ";
for (int i = str.length(); i > 0; i--) {
if(i%3==0){
rs = rs + str.substring(i - 1, i)+ ", ";
}else{
rs = rs + str.substring(i - 1, i);
}
}
str= " ";
for (int i = rs.length(); i > 0; i--) {
str = str + rs.substring(i - 1, i);
}

System.out.println(str);
------解决方案--------------------
public class StringTest {
public static void main(String[] args) {
String a = "fa12d010sf0asd23fa56sd8f+das ";
int length = a.length();
String d = " ";
int lastIndex = length;
while (length > 0) {
length = length - 3;
if (length > 0) {
System.out.println(length);
d += a.substring(length, lastIndex) + ", ";
lastIndex -= 3;

} else {
d += a.substring(0,lastIndex);
}

}
System.out.println(d);

}
}

------解决方案--------------------
来个短的:
str = str.substring(0, str.length() % 3 == 0 ? 3 : str.length() % 3) + str.substring(str.length() % 3 == 0 ? 3 : str.length() % 3, str.length()).replaceAll( "(.{3}) ", ",$1 ");
------
效率不高,纯属娱乐
------解决方案--------------------
public static void main(String[] args) {
String a = "fa12d010sf0asd23fa56sd8f+das ";
int length = a.length();
String d = " ";
int k = length % 3;
d += a.substring(0, k);
length -= k;
int i = k;
while (i < length) {
d += ", " + a.substring(i, i + 3);