Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบว่าสตริงเป็นตัวเลขใน C# - IsDigit, TryParse, Regex

หลายวิธีตรวจสอบว่าสตริงประกอบด้วยตัวเลขเท่านั้น

วิธีที่ 1: LINQ All + Char.IsDigit (Simple)


using System;
using System.Linq;

string str = "3456";
bool isNumber = str.All(c => char.IsDigit(c)); // True

string str2 = "34a6";
bool isNumber2 = str2.All(c => char.IsDigit(c)); // False

วิธีที่ 2: int.TryParse / long.TryParse (แนะนำ - รองรับ Negative, Overflow)


string str = "3456";
bool success = int.TryParse(str, out int value);
// success = true, value = 3456

string str2 = "-3456";
success = int.TryParse(str2, out value); // True, -3456

string str3 = "345678901234567890";
success = long.TryParse(str3, out long lval); // True (64-bit)

string str4 = "3.14";
success = int.TryParse(str4, out value); // False (Decimal Point)

วิธีที่ 3: double/decimal.TryParse (รองรับทศนิยม)


string str = "3.14159";
bool success = double.TryParse(str, out double value); // True

// กำหนด Culture/Style
success = double.TryParse("1,234.56", NumberStyles.Number, CultureInfo.InvariantCulture, out value);
// success = True, value = 1234.56

วิธีที่ 4: Regex (Pattern Matching)


using System.Text.RegularExpressions;

// Integer Only
bool isInt = Regex.IsMatch(str, @"^\d+$");           // Positive Only
bool isIntSigned = Regex.IsMatch(str, @"^-?\d+$");   // With Optional -

// Decimal
bool isDecimal = Regex.IsMatch(str, @"^-?\d+(\.\d+)?$");

ตารางเปรียบเทียบ

Methodรองรับ -รองรับ DecimalOverflow SafePerformanceUse Case
All(IsDigit)✗✗N/AFastPositive Integers Only
int.TryParse✓✗✓FastGeneral Integer
long.TryParse✓✗✓FastLarge Integers
double.TryParse✓✓✓MediumFloating Point
decimal.TryParse✓✓✓MediumFinancial/Precision
Regex✓✓N/ASlowComplex Patterns

Extension Method สำหรับ Reuse


public static class StringExtensions
{
    public static bool IsInteger(this string s) =>
        !string.IsNullOrEmpty(s) && s.All(char.IsDigit);

    public static bool IsNumber(this string s) =>
        double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands,
                       CultureInfo.InvariantCulture, out _);

    public static bool TryParseInt(this string s, out int value) =>
        int.TryParse(s, out value);

    public static int? ToIntOrNull(this string s) =>
        int.TryParse(s, out int v) ? v : null;
}

กรณีใช้งานจริง

  • Input Validation (Forms, API)
  • Parsing Config/CLI Arguments
  • CSV/Log Parsing
  • Game Dev: High Score Parsing

⚠️ ข้อควรระวัง

  • char.IsDigit รองรับ Unicode Digits (٠١٢٣...) - อาจไม่ใช่ที่ต้องการ
  • int.TryParse ไม่รองรับ Group Separator (1,000) โดย Default
  • Empty String: `All` คืน True, `TryParse` คืน False
  • Whitespace: `TryParse` คืน False ถ้าไม่ Trim