繁体   English   中英

我应该如何将带有文本后缀的数字转换为c#中的整数?

[英]How should I convert a number with a text suffix to an integer in c#?

C#将400AMP或6M之类的东西转换成整数的最干净/最好的方法是什么? 我不会总是知道后缀是什么,我只是想要它离开并留下我的号码。

您可以使用正则表达式:

Regex reg = new Regex("[0-9]*");
int result = Convert.ToInt32(reg.Match(input));

它可能不是最干净的方法,但它相当简单(一个单线程),我想象比正则表达式更快(未编译,肯定)。

var str = "400AMP";
var num = Convert.ToInt32(str.Substring(0, str.ToCharArray().TakeWhile(
    c => char.IsDigit(c)).Count()));

或者作为扩展方法:

public static int GetInteger(this string value)
{
    return Convert.ToInt32(str.Substring(0, str.ToCharArray().TakeWhile(
        c => char.IsDigit(c)).Count()));
}

同样,您可以从TakeWhile函数的结果构造数字字符串,如下所示:

public static int GetInteger(this string value)
{
    return new string(str.ToCharArray().TakeWhile(
        c => char.IsNumber(c)).ToArray());
}

没有基准测试他们,所以我不知道哪个更快(虽然我非常怀疑第一个)。 如果你想获得更好的性能,你只需将LINQ(对枚举的扩展方法调用)转换为for循环。

希望有所帮助。

好的,这是一个冗长的解决方案,应该相当快。 它类似于Guffa的中间答案,但是我已经将条件置于循环体内,因为我认为这更简单(并允许我们只获取一次字符)。 这真的是个人品味的问题。

它故意限制它匹配的位数,因为如果字符串是一个溢出Int32的整数,我想我宁愿看到一个异常,而不仅仅是一个大整数:)

请注意,这也处理负数,我不认为到目前为止任何其他解决方案...

using System;

class Test
{
    static void Main()
    {
        Console.WriteLine(ParseLeadingInt32("-1234AMP"));
        Console.WriteLine(ParseLeadingInt32("+1234AMP"));
        Console.WriteLine(ParseLeadingInt32("1234AMP"));
        Console.WriteLine(ParseLeadingInt32("-1234"));
        Console.WriteLine(ParseLeadingInt32("+1234"));
        Console.WriteLine(ParseLeadingInt32("1234"));
   }

    static int ParseLeadingInt32(string text)
    {
        // Declared before loop because we need the
        // final value
        int i;
        for (i=0; i < text.Length; i++)
        {
            char c = text[i];
            if (i==0 && (c=='-' || c=='+'))
            {
                continue;
            }
            if (char.IsDigit(c))
            {
                continue;
            }
            break;
        }
        return int.Parse(text.Substring(0, i));
    }
}

有几种选择......

就像使用正则表达式一样:

int result = int.Parse(Regex.Match(input, @"^\d+").Groups[0].Value);

其中最快的; 只需循环查找数字:

int i = 0;
while (i < input.Length && Char.IsDigit(input, i)) i++;
int result = int.Parse(input.Substring(0, i));

使用LastIndexOfAny查找最后一位数字:

int i = input.LastIndexOfAny("0123456789".ToCharArray()) + 1;
int result = int.Parse(input.Substring(0, i));

(注意:在后缀后面有数字的字符串中断,如“123asdf123”。)

可能最快; 自己解析:

int i = 0;
int result = 0;
while (i < input.Length) {
    char c = input[i];
    if (!Char.IsDigit(c)) break;
    result *= 10;
    result += c - '0';
    i++;
}

如果您只想删除一个未知的后缀,那么我将采用以下方法:

我喜欢一个实用的静态方法,我调用IsInt(string possibleInt),顾名思义,如果字符串将解析为int,则返回True。 您可以将相同的静态方法写入您的实用程序类(如果它已经不存在)并尝试:

       `string foo = "12345SomePostFix";
        while (!Tools.ToolBox.IsInt(foo))
        {
            foo = foo.Remove(foo.Length - 1);
        }
        int fooInt = int.Parse(foo);`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM