转换字(字符串)INT [英] Convert words (string) to Int

查看:202
本文介绍了转换字(字符串)INT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,这个已经做了一百次,但我希望能有一个非常简单的方法来完成这个。我想改变的话一个int。

I'm sure this has been done a hundred times, but i'm hoping there is a really simple way to accomplished this. I'm wanting to change words to an int.

像下面的例子

One = 1
Two = 2
Three = 3

所以基本上,如果我有字符串一都会转换1,即使我能得到一个字符串1,我就可以将其转换。

So basically if I have the string "One" it gets converted to 1, even if I could get back a string "1" I can just convert that.

推荐答案

这样做是为了乐趣。 ..有可能是许多优势情况下,将失败的...

Did this for fun... there's probably many edge cases that would fail...

private static Dictionary<string,long> numberTable=
    new Dictionary<string,long>
        {{"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},{"forty",40},{"fifty",50},{"sixty",60},
        {"seventy",70},{"eighty",80},{"ninety",90},{"hundred",100},
        {"thousand",1000},{"million",1000000},{"billion",1000000000},
        {"trillion",1000000000000},{"quadrillion",1000000000000000},
        {"quintillion",1000000000000000000}};
public static long ToLong(string numberString)
{
    var numbers = Regex.Matches(numberString, @"\w+").Cast<Match>()
         .Select(m => m.Value.ToLowerInvariant())
         .Where(v => numberTable.ContainsKey(v))
         .Select(v => numberTable[v]);
    long acc = 0,total = 0L;
    foreach(var n in numbers)
    {
        if(n >= 1000)
        {
            total += (acc * n);
            acc = 0;
        }
        else if(n >= 100){
            acc *= n;
        }
        else acc += n;          
    }
    return (total + acc)  * ( numberString.StartsWith("minus",
          StringComparison.InvariantCultureIgnoreCase) ? -1 : 1);
}

这篇关于转换字(字符串)INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆