當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Char.IsDigit()用法及代碼示例

在C#中,Char.IsDigit()是一種System.Char結構方法,用於檢查Unicode字符是否可以歸類為十進製數字(基數10)。有效數字將成為UnicodeCategory.DecimalDigitNumber類別的成員。可以通過傳遞不同類型和數量的參數來重載此方法。

  1. Char.IsDigit(Char)方法
  2. Char.IsDigit(String,Int32)方法


Char.IsDigit(Char)方法

此方法用於檢查指定的Unicode字符是否與十進製數字匹配。如果匹配,則返回True,否則返回False。

用法:

public static bool IsDigit(char ch);

參數:

  • ch:必須檢查System.char類型的Unicode字符。

返回類型:如果成功匹配任何十進製數字,則該方法返回True,否則返回False。此方法的返回類型為System.Boolean。

例:

// C# program to illustrate the 
// Char.IsDigit(Char) Method 
using System; 
  
class GFG { 
  
    // Main Method 
    static public void Main() 
    { 
  
        // Declaration of data type 
        bool result; 
  
        // checking if 5 
        // is a digit or not 
        char ch1 = '5'; 
        result = Char.IsDigit(ch1); 
        Console.WriteLine(result); 
  
        // checking if 'c' 
        // is a digit 
        char ch2 = 'c'; 
        result = Char.IsDigit(ch2); 
        Console.WriteLine(result); 
    } 
}
輸出:
True
False

Char.IsDigit(String,Int32)方法

此方法用於檢查指定位置的指定字符串是否與任何十進製數字匹配。如果匹配,則返回True,否則返回False。

用法:

public static bool IsDigit(string str, int index);

參數:


  • Str:這是要評估的System.String類型的必需字符串。
    index:是要比較的字符串中字符的位置,此參數的類型為System.Int32

返回類型:如果該方法成功匹配了指定字符串中指定索引處的任何十進製數字,則該方法返回True,否則返回False。此方法的返回類型為System.Boolean。

異常:

  • 如果str的值為null,則此方法將提供ArgumentNullException
  • 如果索引小於零或大於str中的最後一個位置,則此方法將給出ArgumentOutOfRangeException。

例:

// C# program to illustrate the 
// Char.IsDigit(String, Int32) Method 
using System; 
  
class GFG { 
  
    // Main Method 
    static public void Main() 
    { 
  
        // Declaration of data type 
        bool result; 
  
        // checking for decimal digit in 
        // a string at a desired position 
        string str1 = "GeeksforGeeks"; 
        result = Char.IsDigit(str1, 2); 
        Console.WriteLine(result); 
  
        // checking for decimal digit in a 
        // string at a desired position 
        string str2 = "geeks5forgeeks"; 
        result = Char.IsDigit(str2, 5); 
        Console.WriteLine(result); 
    } 
}
輸出:
False
True

參考:https://docs.microsoft.com/en-us/dotnet/api/system.char.isdigit?view=netframework-4.7.2



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 C# | Char.IsDigit() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。