C# Programming

C#高效字符转整数

Spread the love

将表示数字 (0-9) 的字符转换为其整数等效值是 C# 中的常见任务。本文探讨了四种高效的方法,突出它们的优缺点,以帮助您为特定场景选择最佳方法。

目录

减去 ‘0’

此方法利用 ASCII 和 Unicode 中字符的顺序排列。从数字字符中减去字符 ‘0’ 直接产生其整数等效值。它简洁高效,但仅限于 ASCII 数字 (‘0’ 到 ‘9’)。


using System;

public class CharToIntConversion
{
    public static void Main(string[] args)
    {
        char digitChar = '3';

        if (char.IsDigit(digitChar))
        {
            int intValue = digitChar - '0';
            Console.WriteLine($"'{digitChar}' 的整数值为:{intValue}");
        }
        else
        {
            Console.WriteLine($"'{digitChar}' 不是数字。");
        }
    }
}

使用 char.GetNumericValue()

char.GetNumericValue() 方法提供强大的转换功能,可以处理来自各种 Unicode 范围的数字。但是,它返回一个 double,需要强制转换为 int,并且对于非数字字符返回 -1。


using System;

public class CharToIntConversion
{
    public static void Main(string[] args)
    {
        char digitChar = '7';

        double numericValue = char.GetNumericValue(digitChar);

        if (numericValue != -1)
        {
            int intValue = (int)numericValue;
            Console.WriteLine($"'{digitChar}' 的整数值为:{intValue}");
        }
        else
        {
            Console.WriteLine($"'{digitChar}' 不是数字字符。");
        }
    }
}

使用 char.GetDecimalDigitValue()

类似于 GetNumericValue(),但专门用于十进制数字 (0-9)。它直接返回一个 int,如果输入不是十进制数字则返回 -1,使其高效且简单。


using System;

public class CharToIntConversion
{
    public static void Main(string[] args)
    {
        char digitChar = '9';
        int intValue = char.GetDecimalDigitValue(digitChar);

        if (intValue != -1)
        {
            Console.WriteLine($"'{digitChar}' 的整数值为:{intValue}");
        }
        else
        {
            Console.WriteLine($"'{digitChar}' 不是十进制数字。");
        }
    }
}

使用 int.Parse()

int.Parse() 将字符串表示形式转换为整数。虽然对于单个字符来说效率似乎较低,但在处理字符串或需要强大的错误处理时它是有优势的。如果输入不是有效的整数,它会抛出 FormatException


using System;

public class CharToIntConversion
{
    public static void Main(string[] args)
    {
        char digitChar = '5';

        try
        {
            int intValue = int.Parse(digitChar.ToString());
            Console.WriteLine($"'{digitChar}' 的整数值为:{intValue}");
        }
        catch (FormatException)
        {
            Console.WriteLine($"'{digitChar}' 不是有效的整数。");
        }
    }
}

最佳方法取决于您的上下文。对于简单的 ASCII 数字,减去 ‘0’ 是最快的。对于更广泛的 Unicode 支持和错误处理,GetNumericValue()GetDecimalDigitValue() 更可取。int.Parse() 提供最强大的错误处理,但对于单个字符效率最低。始终适当地处理潜在的错误。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注