不久前看到sql server 可以把一串数字转换为中文繁体字,于是我决定自己实现以下。测试:$ ./a 123456789壹亿贰仟叁佰肆拾伍万陆仟柒佰捌拾玖整$ ./a 10203壹万零贰佰零叁整代码如下,欢迎大家指正:
/*currency.c
阿拉伯数字转换为中文数字
author: ludi 2013.07
*/
#include <stdio.h>
#include <string.h>
char *shuzi[10] = {"零","壹", "贰","叁", "肆", "伍", "陆", "柒", "捌", "玖"};
char *danwei[6] = {"整", "万", "亿", "万亿", "千亿", "亿亿"};
static char s_buf[1024];
static int s_len;
void out0(char *str)
{
int len, i;
len = strlen(str);
if(len&1){
fprintf(stderr, "out(): bad len %d\n", len);
return;
}
for(i = len-1; i >= 0; i -= 2){
s_buf[s_len++] = str[i];
s_buf[s_len++] = str[i-1];
}
//for(;*str; ++str){printf("%c", *str);}
}
void out(char *dw, char num)
{
char tmp[64] = "";
if(num == '0'){
return;
}
strcpy(tmp, shuzi[num - '0']);
strcat(tmp, dw);
out0(tmp);
}
int format(char *numstr)
{
int len, i, base;
if(!numstr){
return -1;
}
len = strlen(numstr);
for(i = len-1, base = 0; i >= 3; i -= 4, ++base){
out(danwei[base], numstr[i-0]);
out("拾", numstr[i-1]);
if(numstr[i-0] != '0' && numstr[i-1] == '0')out0("零");
out("佰", numstr[i-2]);
if(numstr[i-1] != '0' && numstr[i-2] == '0')out0("零");
out("仟", numstr[i-3]);
if(numstr[i-2] != '0' && numstr[i-3] == '0')out0("零");
}
while(i>=0){
out(danwei[base], numstr[i-0]);
if(i<1)break;
out("拾", numstr[i-1]);
if(i<2)break;
out("佰", numstr[i-2]);
if(i<3)break;
out("仟", numstr[i-3]);
}
return 0;
}
int main(int argc, char *argv[])
{
char *str = NULL;
int i;
if(argc < 2){return fprintf(stderr, "usage: currency number\n eg. currency 123456789\n"); }
str = argv[1];
format(str);
printf("\n");
for(i = s_len-1; i >= 0; --i){putchar(s_buf[i]);}
printf("\n");
return 0;
}