我有一个C#方法,将整数转换为英文单词对应的;但是,我如何实现这一点,以便它可以使用字符串。
例如,如果我有以下字符串:
有一只狗。狗吃了1000块骨头。吃完之后,他非常困倦。他睡了12个小时。
我希望它解析它并返回:
有一只狗。狗吃了一千块骨头。吃完之后,他非常困倦。他睡了十二个小时。
如何从句子中取出数字并使用转换方法(如下)?
public static string NumberToWords(int number)
{
if (number == 0)
return "zero";
if (number < 0)
return "minus " + NumberToWords(Math.Abs(number));
string words = "";
if ((number / 1000000) > 0)
{
words += NumberToWords(number / 1000000) + " million ";
number %= 1000000;
}
if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += NumberToWords(number / 100) + " hundred ";
number %= 100;
}
if (number > 0)
{
if (words != "")
words += "and ";
var unitsMap = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
var tensMap = new[] { "zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
if (number < 20)
words += unitsMap[number];
else
{
words += tensMap[number / 10];
if ((number % 10) > 0)
words += "-" + unitsMap[number % 10];
}
}
return words;
}
我试过像这样做一个foreach,但它没有工作......
var matches = Regex.Matches(myString, "[0-9]+");
foreach(var match in matches)
{
NumberToWords(match);
}
答案 0 :(得分:4)
您可以使用Split
和LINQ
:
var input = "There was a dog. The dog ate 1000 bones. After eating, he was very sleepy. He slept for 12 hours.";
var invalidChars = new [] { ',', ';', '-', '.' };
var words = input.Split(' ')
.Select(x =>
{
if (x.All(char.IsDigit) || x.Trim(invalidChars).All(char.IsDigit))
return NumberToWords(int.Parse(x.Trim(invalidChars)));
return x;
});
var output = string.Join(" ", words);
顺便说一下,我认为NumberToWord
方法工作正常。
答案 1 :(得分:1)
您可以使用Selman22的方法,但如果您没有使用带有LINQ的.NET版本,您可以使用RegularExpression替换功能而不是匹配。
http://msdn.microsoft.com/en-us/library/cft8645c(v=vs.110).aspx
你只需要一个MatchEvaluator委托:
static string matchEvaluator(Match m)
{
return NumberToWords(int.Parse(m.ToString()));
}
答案 2 :(得分:1)
更简单的方法是使用Regex.Replace方法{/ 3}}。
string input = "There was a dog. The dog ate 1000 bones. After eating, he was very sleepy. He slept for 12 hours.";
string output = Regex.Replace(input, @"\d+", m => NumberToWords(int.Parse(m.Value)));
答案 3 :(得分:0)
对现有代码的最小更改:
string s = "There was a dog. The dog ate 1000 bones. After eating, he was very sleepy. He slept for 12 hours.";
foreach (var match in Regex.Matches(s, "[0-9]+"))
{
string number = match.ToString();
s = s.Replace(number, NumberToWords(int.Parse(number)));
}
Console.WriteLine(s);