之前在CSDN論壇裏,看有人Show了一些把中文大寫轉換成阿拉伯數字的程序代碼,自己也用Java語言實現了程序設計,基本上能夠實現十萬億以內的任何數字的轉換。之前也帖出自己的實現代碼。
但我個人認爲,把大寫轉換爲數字實際上是沒有多少意義的。因爲很少有把大寫轉爲數字的,大多數都是把數字轉換爲大寫。何況把大寫轉爲數字並不是一件很容易的事情,因爲漢語大寫有很多種說法,比如說:101,它的漢語說法可以有好多種:
(一)、百零一
(二)、一百零一
(三)、一百又一
(四)、幺零幺
因此,要實現起來其實是很難的。而且還要防止用戶輸入大小寫不固定,一會輸入“一百零一”,一會又輸入“壹佰零壹”,或者是二者的雜合體。形式千變萬化,何況這一個數字就可以有這麼多種,還有那麼多特殊的數字呢?除非用成統一標準的輸入。否則是很容易出現問題的。
但是,數字轉換成大寫卻是很實用的,平時去銀行用得比較多,只要涉及金錢的時候,基本上都要求用大寫。所以,這種轉換看來是符合要求,因此,我用C#代碼實現了其功能,並將用戶輸入用“,”分隔成三個一組的形式,可以實現百萬億級別的數字轉換。下面我帖出部分代碼,大家指正:
其他輸入驗證我就不帖出來了,只把核心代碼帖出來
- class Chinese
- {
- public string returnResult(long num)
- {
- string numStr = num.ToString();
- //主要理念是把數字字符串最終分隔爲四個一組四個一組的,不足的不管。
- if (numStr.Length > 8 & numStr.Length < 16)
- {
- //定義一個數組,存儲整個字條串分隔後的字符串。然後兩次遞歸調用。
- //調用完全後,得到總的大寫字符串。
- string[] firstSplit = new string[2];
- firstSplit[0] = numStr.Substring(0, numStr.Length - 8);
- firstSplit[1] = numStr.Substring(numStr.Length - 8, 8);
- string result1 = getString(firstSplit[0]) + "億";
- string result2 = getString(firstSplit[1]);
- return result1 + result2;
- }
- else
- {
- return getString(numStr);
- }
- }
- //進行一次遞歸調用,得到兩組四位數字的大字字串
- public string getString(string str)
- {
- if (str.Length > 4)
- {
- string[] secondSplit = new string[2];
- secondSplit[0] = str.Substring(0, str.Length - 4);
- secondSplit[1] = str.Substring(str.Length - 4, 4);
- string result1 = getRe(secondSplit[0]);
- string result2 = getRe(secondSplit[1]);
- //確定是否加“萬”字
- if (!secondSplit[0].Equals("0000"))
- {
- result1 += "萬";
- }
- return result1 + result2;
- }
- else
- {
- return getRe(str);
- }
- }
- int[] value = { 1000, 100, 10 };
- //將四位數以內的字符串返回爲正確的大寫稱呼 比如1234 返回:一千二百三十四
- public string getRe(string doWith)
- {
- char[] number = doWith.ToCharArray();
- int length = number.Length;
- string re = "";
- for (int i = 0; i < length; i++)
- {
- switch (number[i])
- {
- case '0':
- if (re.EndsWith("零"))
- {
- re += "";
- }
- else
- {
- re += "零";
- }
- break;
- case '1':
- re += "壹";
- break;
- case '2':
- re += "貳";
- break;
- case '3':
- re += "叄";
- break;
- case '4':
- re += "肆";
- break;
- case '5':
- re += "伍";
- break;
- case '6':
- re += "陸";
- break;
- case '7':
- re += "柒";
- break;
- case '8':
- re += "捌";
- break;
- case '9':
- re += "玖";
- break;
- }
- int index = (int)Math.Pow(10, length - i - 1);
- if (number[i].ToString() == "0")
- {
- index = -1;
- }
- switch (index)
- {
- case 1000:
- re += "仟";
- break;
- case 100:
- re += "佰";
- break;
- case 10:
- re += "拾";
- break;
- }
- }
- if (re.EndsWith("零"))
- {
- re = re.Substring(0, re.Length - 1);
- }
- return re;
- }
- }