Skip to content

Instantly share code, notes, and snippets.

@cheng470
Created September 26, 2018 14:29
Show Gist options
  • Save cheng470/4beb6eda393611fb37388cd4d22cc17b to your computer and use it in GitHub Desktop.
Save cheng470/4beb6eda393611fb37388cd4d22cc17b to your computer and use it in GitHub Desktop.
生成中文书籍章节
package com.cheng470;
/**
* <p>
* Description:生成中文书籍章节
* </p>
*
* @author XuJianCheng
* @version 1.0
* @since 2018/9/23
*/
public class GenChapterName {
static String[] word = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
static String[] unit = {"", "十", "百", "千", "万", "十万", "百万"};
static String pre = "第";
static String suf = "章";
public static void main(String[] args) {
int num = 1234;
for (int i = 1; i <= num; i++) {
System.out.println(numToWord(i));
}
}
private static String numToWord(int num) {
String str = String.valueOf(num);
StringBuilder result = new StringBuilder(pre);
boolean flag = false; // 是否前面扫描到0
for (int i = 0; i < str.length(); i++) {
int n = str.charAt(i) - '0';
if (n == 0) {
flag = true;
continue;
}
// 用十替换一十
if (str.length() == 2 && i == 0 && n == 1) {
result.append(unit[str.length() - i - 1]);
continue;
}
if (flag) {
result.append(word[0]);
flag = false;
}
result.append(word[n]).append(unit[str.length() - i - 1]);
}
result.append(suf);
return result.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment