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

Chu*_*bur 2 c# string

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

cjk*_*cjk 13

您可以使用正则表达式:

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


Nol*_*rin 6

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

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

或者作为扩展方法:

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

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

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

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

希望有所帮助.


Jon*_*eet 6

好的,这是一个冗长的解决方案,应该相当快.它类似于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));
    }
}
Run Code Online (Sandbox Code Playgroud)