从一个字符串中解析一个数字,其中包含非数字

ton*_*ony 12 c#

我正在研究.NET项目,我试图只解析字符串中的数值.例如,

string s = "12ACD";
int t = someparefun(s); 
print(t) //t should be 12
Run Code Online (Sandbox Code Playgroud)

有几个假设

  1. 字符串模式始终是数字后跟字符.
  2. 数字部分始终为一位或两位数值.

是否有任何C#预定义函数来解析字符串中的数值?

Bob*_*bby 30

没有这样的功能,至少我不知道.但是一种方法是使用正则表达式删除不是数字的所有内容:

using System;
using System.Text.RegularExpressions;

int result =
    // The Convert (System) class comes in pretty handy every time
    // you want to convert something.
    Convert.ToInt32(
        Regex.Replace(
            "12ACD",  // Our input
            "[^0-9]", // Select everything that is not in the range of 0-9
            ""        // Replace that with an empty string.
    ));
Run Code Online (Sandbox Code Playgroud)

该功能将产生1212ABC,所以如果你需要能够处理负数,你需要一个不同的解决方案.这也是不安全的,如果你只传递非数字,它将产生一个FormatException.以下是一些示例数据:

"12ACD"  =>  12
"12A5"   =>  125
"CA12A"  =>  12
"-12AD"  =>  12
""       =>  FormatException
"AAAA"   =>  FormatException
Run Code Online (Sandbox Code Playgroud)

使用更简洁但更安全的方法int.TryParse():

using System;
using System.Text.RegularExpression;

public static int ConvertToInt(String input)
{
    // Replace everything that is no a digit.
    String inputCleaned = Regex.Replace(input, "[^0-9]", "");

    int value = 0;

    // Tries to parse the int, returns false on failure.
    if (int.TryParse(inputCleaned, out value))
    {
        // The result from parsing can be safely returned.
        return value;
    }

    return 0; // Or any other default value.
}
Run Code Online (Sandbox Code Playgroud)

一些示例数据:

"12ACD"  =>  12
"12A5"   =>  125
"CA12A"  =>  12
"-12AD"  =>  12
""       =>  0
"AAAA"   =>  0
Run Code Online (Sandbox Code Playgroud)

或者如果你只想要字符串中的第一个数字,基本上停止会遇到不是数字的东西,我们突然也可以轻松地处理负数:

using System;
using System.Text.RegularExpression;

public static int ConvertToInt(String input)
{
    // Matches the first numebr with or without leading minus.
    Match match = Regex.Match(input, "-?[0-9]+");

    if (match.Success)
    {
        // No need to TryParse here, the match has to be at least
        // a 1-digit number.
        return int.Parse(match.Value);
    }

    return 0; // Or any other default value.
}
Run Code Online (Sandbox Code Playgroud)

我们再次测试它:

"12ACD"  =>  12
"12A5"   =>  12
"CA12A"  =>  12
"-12AD"  =>  -12
""       =>  0
"AAAA"   =>  0
Run Code Online (Sandbox Code Playgroud)

总的来说,如果我们谈论用户输入,我会考虑根本不接受无效输入,只使用int.TryParse()没有一些额外的魔法,并且在失败时通知用户输入不是最理想的(并且可能再次提示输入有效数字).

  • @Randoplho:我知道,我知道......我知道他现在有两个问题,但没有一个是我的.,P (10认同)
  • 危险威尔罗宾逊!危险!正面表达未来!破坏!破坏! (8认同)

Ahm*_*eed 15

正如鲍比展示的那样,正则表达式是一种方法.

根据您的假设,另一种方法是以TakeWhile这种方式使用(TryParse为了额外的安全性):

string input = "12ACD";
string digits = new string(input.TakeWhile(c => Char.IsDigit(c)).ToArray());
int result;
if (Int32.TryParse(digits, out result))
{
    Console.WriteLine(result);
}
Run Code Online (Sandbox Code Playgroud)

当然,代码的目的不会立即弹出给读者,因为他们的大部分时间将用于解密TakeWhile被转换为a 的部分string.

  • 如果将TakeWhile调用封装到另外的GetStartingDigits函数中,则应该很容易通读代码. (4认同)