我有例如 10%, 13%的示例,我必须将它们转换为 分别为10%和13%。
我该怎么做,我必须将长字符串中的这个字符串与之匹配,并需要将其转换为数字,下面的代码可以找到
10%和10%如何找到10%并将其转换为数字
代码
public StringBuilder extractPercentage(string html)
{
StringBuilder formattedString = new StringBuilder();
foreach (Match m in Regex.Matches(html, @"\d+\%|\s\bpercent\b)"))
{
var a = m.Value;
formattedString.Append(m.Value + "<br/>");
}
return formattedString;
}
结果:
100%-是
100%是
我在这里有两种情况:识别数量并带有百分比并转换为数字
答案 0 :(得分:0)
下面的代码应该可以满足您的需求:
static string ParseEnglish(string number)
{
number= number.Replace("percent", "").Trim();
string[] words = number.ToLower().Split(new char[] { ' ', '-', ',' }, StringSplitOptions.RemoveEmptyEntries);
string[] ones = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
string[] teens = { "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
string[] tens = { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
Dictionary<string, int> modifiers = new Dictionary<string, int>() {
{"billion", 1000000000},
{"million", 1000000},
{"thousand", 1000},
{"hundred", 100}
};
if (number == "eleventy billion")
return int.MaxValue.ToString(); // 110,000,000,000 is out of range for an int!
int result = 0;
int currentResult = 0;
int lastModifier = 1;
foreach (string word in words)
{
if (modifiers.ContainsKey(word))
{
lastModifier *= modifiers[word];
}
else
{
int n;
if (lastModifier > 1)
{
result += currentResult * lastModifier;
lastModifier = 1;
currentResult = 0;
}
if ((n = Array.IndexOf(ones, word) + 1) > 0)
{
currentResult += n;
}
else if ((n = Array.IndexOf(teens, word) + 1) > 0)
{
currentResult += n + 10;
}
else if ((n = Array.IndexOf(tens, word) + 1) > 0)
{
currentResult += n * 10;
}
else if (word != "and")
{
throw new ApplicationException("Unrecognized word: " + word);
}
}
}
int ReturnValue = result + currentResult * lastModifier;
return ReturnValue.ToString () + "%";
}
此答案是对本帖子答案的修改: Convert words (string) to Int