在批量使用測試帳號的時候,須要對帳號進行標記,通常用username字段,以前的策略是統一的名稱+用戶編號(測試用戶的編號,非用戶id),因爲需求變動,用戶username不容許使用數字了,因此須要把數字轉成漢字來進行標記。 下面分享集中方法:java
private static String change1(int n) {// 數字轉換成漢字表示 String[] c = {"零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"}; String ss = n + "";//把輸入的內容轉換成String類型字符串 StringBuilder builder = new StringBuilder(""); int j; for (int i = 0; i < ss.length(); i++) { for (j = 0; j <= 9; j++) {// 遍歷ss字符串中每一個字符並追加到builder中 if (ss.charAt(i) == j + '0') { break; } } builder.append(c[j]);//往builder對象中追加獲取的字符 } return builder.toString();//返回該字符串 } private static String change2(int n) {// 數字轉換成漢字表示 String[] c = {"零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"}; String ss = n + "";//把輸入的內容轉換成String類型字符串 StringBuilder builder = new StringBuilder(""); for (int i = 0; i < ss.length(); i++) { char c1 = ss.charAt(i); int i1 = Integer.parseInt(c1 + ""); builder.append(c[i1]);//往builder對象中追加獲取的字符 } return builder.toString();//返回該字符串 } private static String change3(int n) {// 數字轉換成漢字表示 String[] c = {"零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"}; String ss = n + "";//把輸入的內容轉換成String類型字符串 StringBuilder builder = new StringBuilder(""); IntStream.range(0, ss.length()).forEach(x -> builder.append(c[Integer.valueOf(ss.charAt(x) + "")])); return builder.toString();//返回該字符串 } private static String change4(int n) {// 數字轉換成漢字表示 String[] c = {"零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"}; return IntStream.range(0, (n + "").length()).mapToObj(x -> c[Integer.valueOf((n + "").charAt(x) + "")]).collect(Collectors.joining()).toString(); } private static String change5(int n) {// 數字轉換成漢字表示 String[] c = {"零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"}; return Arrays.asList((n + "").toCharArray()).stream().map(x -> c[Integer.valueOf(x + "")]).collect(Collectors.joining()).toString(); }
因爲使用了腳本語言Groovy,因此功能仍是須要用Groovy寫的,下面是Groovy版本:編程
static String[] chineses = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"] static String[] capeChineses = ["零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"] /** * 將int類型轉化爲漢子數字,對於3位數的數字自動補零 * @param i * @return */ static String getChinese(int i) { if (i <= 0) return "零零零" String num = (i + EMPTY).collect { x -> chineses[changeStringToInt(x)] }.join() num.length() > 2 ? num : getManyString(chineses[0] + EMPTY, 3 - num.length()) + num } /** * 將int類型轉化漢字大寫數字表示 * @param i * @return */ static String getCapeChinese(int i) { (i + EMPTY).collect { x -> capeChineses[changeStringToInt(x)] }.join() }
不得不說,腳本語言真香。app