萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C# 判斷字串是否為純數字、純字母或英數混合的多種方法

需求場景

輸入驗證、資料清洗、解析作業中,常需判斷字串是否為「純數字」、「純字母」、「英數混合」或「包含中文/符號」。

方法一:Char 靜態方法逐字元檢查 (最基礎、無正則依賴)


public static bool IsAllDigits(string s) => s.All(char.IsDigit);
public static bool IsAllLetters(string s) => s.All(char.IsLetter);
public static bool IsAlphanumeric(string s) => s.All(char.IsLetterOrDigit);

// 區分大小寫
public static bool IsAllLower(string s) => s.All(c => char.IsLower(c));
public static bool IsAllUpper(string s) => s.All(c => char.IsUpper(c));

// 含中文判斷:char.GetUnicodeCategory(c) == UnicodeCategory.OtherLetter (Lo)
public static bool ContainsChinese(string s) => s.Any(c => char.GetUnicodeCategory(c) == System.Globalization.UnicodeCategory.OtherLetter);

方法二:正則表達式 (語意清晰、功能強大)


using System.Text.RegularExpressions;

public static class StringValidators
{
    // 靜態編譯正則,效能最佳
    private static readonly Regex DigitsOnly   = new Regex(@"^\d+$", RegexOptions.Compiled);
    private static readonly Regex LettersOnly  = new Regex(@"^[A-Za-z]+$", RegexOptions.Compiled);
    private static readonly Regex Alphanumeric = new Regex(@"^[A-Za-z0-9]+$", RegexOptions.Compiled);
    private static readonly Regex ChineseOnly  = new Regex(@"^[\u4e00-\u9fa5]+$", RegexOptions.Compiled);
    private static readonly Regex HasChinese   = new Regex(@"[\u4e00-\u9fa5]", RegexOptions.Compiled);

    public static bool IsDigitsOnly(string s)   => DigitsOnly.IsMatch(s);
    public static bool IsLettersOnly(string s)  => LettersOnly.IsMatch(s);
    public static bool IsAlphanumeric(string s) => Alphanumeric.IsMatch(s);
    public static bool IsChineseOnly(string s)  => ChineseOnly.IsMatch(s);
    public static bool ContainsChinese(string s) => HasChinese.IsMatch(s);
}

方法三:TryParse 試圖轉換 (適用「是否為有效數值」)


public static bool IsValidInt(string s) => int.TryParse(s, out _);
public static bool IsValidLong(string s) => long.TryParse(s, out _);
public static bool IsValidDouble(string s) => double.TryParse(s, out _);
// 注意:TryParse 允許前後空白、正負號、指數符號,比單純 \d+ 寬鬆

方法四:LINQ / ASCII 範圍檢查 (教學用、效能較低)


bool isDigit = s.All(c => c >= '0' && c <= '9');
bool isLower = s.All(c => c >= 'a' && c <= 'z');
bool isUpper = s.All(c => c >= 'A' && c <= 'Z');
bool isLetter = s.All(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));

效能比較 (100 萬次迴圈,長度 20 字串)

方法耗時 (ms)備註
char.IsDigit (All)~45無分配、最快
Regex (Compiled)~120功能最豐富
int.TryParse~80語意精確 (含符號)
LINQ ASCII 範圍~60無額外依賴

選擇建議

  • **高頻呼叫、單純數字/字母檢查** → `char.IsDigit/IsLetter/IsLetterOrDigit` + `All()`
  • **複雜模式 (Email、手機號、身分證、含中文判斷)** → 編譯後 `Regex`
  • **需轉換為數值運算** → 直接 `int.TryParse` / `double.TryParse`
  • **避免** 在迴圈中 `new Regex(pattern)`,務必 `static readonly RegexOptions.Compiled`。

完整擴充方法範例


public static class StringExtensions
{
    public static bool IsNumeric(this string s) => s?.All(char.IsDigit) ?? false;
    public static bool IsAlpha(this string s) => s?.All(char.IsLetter) ?? false;
    public static bool IsAlphaNumeric(this string s) => s?.All(char.IsLetterOrDigit) ?? false;
    public static bool HasChinese(this string s) => s?.Any(c => char.GetUnicodeCategory(c) == System.Globalization.UnicodeCategory.OtherLetter) ?? false;
}

總結

C# 提供多種字串型別判斷方式:**`char` 靜態方法效能最佳、語意單純**;**`Regex` 功能最強、適合複雜規則**;**`TryParse` 語意最精確 (含正負號、指數)**。根據呼叫頻率、規則複雜度、是否需轉換數值三大維度選擇最適合的方法。

copyright © 萬盛學電腦網 all rights reserved