public class StringTest {
public void toConvert(String strNum){
//去除字符串最前面的0
long lngNum = Long.parseLong(strNum);
StringBuffer str = new StringBuffer(String.valueOf(lngNum));
System.out.println("1:" + str);
//反转字符串
str = str.reverse();
System.out.println("2:" + str);
//定义单位
String[] strAry = {"","十","百","千","万","十","百","千","亿","十","百","千","万"};
StringBuffer strResult = new StringBuffer();
for(int i=0; i<str.length(); i++){
strResult.append(strAry[i]);
strResult.append(toUpper(Integer.parseInt(str.substring(i,i+1))));
}
strResult = strResult.reverse();
System.out.println("3:" + strResult);
//替换
toReplace(strResult,"零十","零");
toReplace(strResult,"零百","零");
toReplace(strResult,"零千","零");
toReplace(strResult,"零万","万");
toReplace(strResult,"零零","零");
System.out.println("4:" + strResult);
String myStr = strResult.toString();
if(myStr.charAt(myStr.length() - 1) == '零'){
myStr = myStr.substring(0,myStr.length()-1);
}
System.out.println("5:" + myStr);
}
//将数字转换为大写
public String toUpper(int n)
{
String s = "";
switch(n){
case 0:s = "零";break;
case 1:s = "一";break;
case 2:s = "二";break;
case 3:s = "三";break;
case 4:s = "四";break;
case 5:s = "五";break;
case 6:s = "六";break;
case 7:s = "七";break;
case 8:s = "八";break;
case 9:s = "九";break;
}
return s;
}
//替换字符串中的“零”
public void toReplace(StringBuffer strTemp,String oldStr,String newStr){
while(strTemp.indexOf(oldStr) >= 0){
strTemp = strTemp.replace(strTemp.indexOf(oldStr),strTemp.indexOf(oldStr) + oldStr.length(),newStr);
}
}
public static void main(String[] args) {
StringTest u = new StringTest();
u.toConvert("100");
}
}
|
|