Is there a way to convert number words to Integers?

前端 未结 16 2269
北恋
北恋 2020-11-22 06:14

I need to convert one into 1, two into 2 and so on.

Is there a way to do this with a library or a class or anythi

16条回答
  •  没有蜡笔的小新
    2020-11-22 06:58

    This is the c# implementation of the code in 1st answer:

    public static double ConvertTextToNumber(string text)
    {
        string[] units = new string[] {
            "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
            "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
            "sixteen", "seventeen", "eighteen", "nineteen",
        };
    
        string[] tens = new string[] {"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
    
        string[] scales = new string[] { "hundred", "thousand", "million", "billion", "trillion" };
    
        Dictionary numWord = new Dictionary();
        numWord.Add("and", new ScaleIncrementPair(1, 0));
        for (int i = 0; i < units.Length; i++)
        {
            numWord.Add(units[i], new ScaleIncrementPair(1, i));
        }
    
        for (int i = 1; i < tens.Length; i++)
        {
            numWord.Add(tens[i], new ScaleIncrementPair(1, i * 10));                
        }
    
        for (int i = 0; i < scales.Length; i++)
        {
            if(i == 0)
                numWord.Add(scales[i], new ScaleIncrementPair(100, 0));
            else
                numWord.Add(scales[i], new ScaleIncrementPair(Math.Pow(10, (i*3)), 0));
        }
    
        double current = 0;
        double result = 0;
    
        foreach (var word in text.Split(new char[] { ' ', '-', '—'}))
        {
            ScaleIncrementPair scaleIncrement = numWord[word];
            current = current * scaleIncrement.scale + scaleIncrement.increment;
            if (scaleIncrement.scale > 100)
            {
                result += current;
                current = 0;
            }
        }
        return result + current;
    }
    
    
    public struct ScaleIncrementPair
    {
        public double scale;
        public int increment;
        public ScaleIncrementPair(double s, int i)
        {
            scale = s;
            increment = i;
        }
    }
    

提交回复
热议问题