哎呀呀第一次写博客,有点小激动啊~~,整理一下之前写过的代码吧
用正则表达式实现了一个将阿拉伯数字转化为中文读法的功能.只支持到千万
import java.io.*;
/**
* Created by Administrator on 2016/8/5.
*/
public class MynumTrans {
public static void main(String[] args) {
try(
FileOutputStream fileOutputStream=new FileOutputStream("result.txt");
FileInputStream fileInputStream=new FileInputStream("text.txt");
OutputStreamWriter outputStreamWriter=new OutputStreamWriter(fileOutputStream,"UTF-8");
InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream,"UTF-8");
BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
BufferedWriter bufferedWriter=new BufferedWriter(outputStreamWriter);
)
{
String str;
int percent=0;
while ((str=bufferedReader.readLine())!=null){
bufferedWriter.write(transwan(Integer.parseInt(str)));
bufferedWriter.newLine();
Thread.sleep(100);
percent++;
System.out.printf("\r[");
for (int i = 0; i <percent ; i++) {
System.out.printf("=");
}
System.out.printf(">>]");
System.out.printf("\t%.2f%%", (float)percent);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static String transwan(int num){
if(num>=100000000){
return "数太大了";
}
StringBuilder stringBuilder=new StringBuilder();
if(num>=10000){
stringBuilder.append(transqian(num/10000)).append("万").append(transqian(num%10000));
}else{
stringBuilder.append(transqian(num));
}
if(stringBuilder.length()>1){
if (stringBuilder.lastIndexOf("零")==stringBuilder.length()-1){
stringBuilder.deleteCharAt(stringBuilder.length()-1);
}
}
return stringBuilder.toString();
}
public static String transqian(int num){
String[] shu={"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append(shu[num/1000]).append("千").append(shu[num/100%10]).append("百")
.append(shu[num/10%10]).append("十").append(shu[num%10]);
int index=-1;
while ((index=stringBuilder.indexOf("零",index+1))!=-1){
if (index<stringBuilder.length()-1){
stringBuilder.deleteCharAt(index+1);
}
}
index=0;
while ((index=stringBuilder.indexOf("零零",index))!=-1){
if(index<stringBuilder.length()){
stringBuilder.deleteCharAt(index);
}
}
if (stringBuilder.length()>1){
if (stringBuilder.lastIndexOf("零")==stringBuilder.length()-1){
stringBuilder.deleteCharAt(stringBuilder.length()-1);
}
if (stringBuilder.indexOf("零")==0){
stringBuilder.deleteCharAt(0);
}
}
if (stringBuilder.indexOf("一十")==1){
stringBuilder.deleteCharAt(0);
}
return stringBuilder.toString();
}
}