2012-02-10 168 views
0

我在尋找一個c#函數,它將字數轉換爲相對數。如何將字數轉換爲數字

有關示例,千25應該被轉換成1025

任何人的早期幫助表示讚賞。

+2

向我們展示你嘗試過什麼... – Marco 2012-02-10 10:06:52

+0

你會發現這個答案有用:http://stackoverflow.com/a/1077651/104435它是僞代碼,因此您必須自行將其轉換爲C# – soniiic 2012-02-10 10:08:06

+1

但問題本身很有趣。有這樣的圖書館嗎?哪一個使用?這不是你應該推出自己的東西。 – 2012-02-10 10:08:47

回答

3

已經測試過它可以處理包含多個數字的字符串。

用法:findNumbers(「成本是五百二十九千三百二十六美元和二十三美分」);

輸出:「成本是529326美元和23美分」

Dictionary<string, string> theNumbers = new Dictionary<string, string>(); 
    string numstring = "zero=0;one=1;two=2;three=3;four=4;five=5;six=6;seven=7;eight=8;nine=9;ten=10;eleven=11;twelve=12;thirteen=13;fourteen=14;fifteen=15;sixteen=16;seventeen=17;eighteen=18;nineteen=19;twenty=20;thirty=30;fourty=40;fifty=50;sixty=60;seventy=70;eighty=80;ninety=90;hundred=100;thousand=1000;"; 
    theNumbers = numstring.TrimEnd(';').Split(';').ToDictionary(item => item.Split('=')[0], item => item.Split('=')[1]); 
    private string findNumbers(string input) 
    { 
     string tmp = "", tmpout = "", output = ""; 
     input = input.Replace("hundred and", "hundred"); 
     foreach (string word in input.Split(' ')) 
     { 
      if (theNumbers.TryGetValue(word, out tmp)) 
      { 
       if (tmpout != "") tmpout += " "; 
       tmpout += tmp; 
      } else 
      { 
       if (tmpout != "") output += " " + addNumbers(tmpout); 
       tmpout = ""; 
       if (output != "") output += " "; 
       output += word; 
      } 
     } 
     if (tmpout != "") { 
      tmpout = addNumbers(tmpout); 
      if (output != "") output += " "; 
      output += tmpout; 
     } 
     return output; 
    } 
    private string addNumbers(string input) 
    { 
     int output = 0; 
     int output2 = 0; 
     foreach (string num in input.Split(' ')) 
     { 
      if (output > 999) 
      { 
       output2 = output; 
       output = 0; 
      } 
      if (Int32.Parse(num) > 99) 
      { 
       output = output * Int32.Parse(num); 
      } else 
      { 
       output = output + Int32.Parse(num); 
      } 
     } 
     return (output + output2).ToString(); 
    }