整数转换成中文读法的字符串

整数转换成中文读法的字符串

[2020.05.12]
如:
1200001234 读作 "一十二亿零一千二百三十四"

//util.h
#include <string>
std::string i2a(int val);
std::string inThousand(unsigned num);

std::string i2a(int val)
{
    static const std::string unit[] = {
        "亿", "万"};
    unsigned num;
    unsigned level = 1e8;
    unsigned tenThousand = 1e4;
    unsigned oneThousand = 1e3;
    unsigned unit_index = 0;
    unsigned segment;
    std::string ans, zero, negative;
    if (val < 0)
    {
        negative = "负";
        num = -val;
    }
    else
    {
        num = val;
    }
    while (num)
    {
        segment = num / level;
        if (segment < oneThousand && !ans.empty() && zero.empty())
        {
            zero = "零";
        }
        if (segment)
        {
            ans += zero + inThousand(segment);
            if (unit_index < sizeof(unit) / sizeof(unit[0]))
            {
                ans += unit[unit_index];
            }
            zero = "";
        }
        num %= level;
        level /= tenThousand;
        unit_index++;
    }
    if (ans.empty())
    {
        return "零";
    }
    return negative + ans;
}

std::string inThousand(unsigned num)
{
    static const std::string code[] = {
        "零", "一", "二", "三",
        "四", "五", "六", "七",
        "八", "九"};
    static const std::string unit[] = {
        "千", "百", "十"};
    num %= 10000;
    unsigned level = 1000;
    unsigned unit_index = 0;
    unsigned digit;
    std::string ans, zero;
    while (num)
    {
        digit = num / level;
        if (digit)
        {
            ans += zero + code[digit];
            if (unit_index < sizeof(unit) / sizeof(unit[0]))
            {
                ans += unit[unit_index];
            }
            if (!zero.empty())
            {
                zero = "";
            }
        }
        else if (!ans.empty() && zero.empty())
        {
            zero = "零";
        }
        num %= level;
        level /= 10;
        unit_index++;
    }
    if (ans.empty())
    {
        ans = "零";
    }
    return ans;
}

测试代码

//main.cpp
#include "util.h"
#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    int num;
    while (cin >> num) {
        cout << num << " is " << i2a(num) << endl;
    }
    return 0;
}

编译

g++ main.cpp -o do

运行结果

cpp$$ ./do
0 1011 1200001234 2000000101 -1 -2034560987 -2000000101
0 is 零
1011 is 一千零一十一
1200001234 is 一十二亿零一千二百三十四
2000000101 is 二十亿零一百零一
-1 is 负一
-2034560987 is 负二十亿三千四百五十六万零九百八十七
-2000000101 is 负二十亿零一百零一

运行结果符合预期

posted @ 2020-05-12 12:35  HorseShoe2016  阅读(575)  评论(0编辑  收藏  举报