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


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


在C#中,Char.TryParse()是Char類方法,用於將值從給定的字符串轉換為其等效的Unicode字符。其性能優於Char.Parse()方法。

用法:

public static bool TryParse(string str, out char result)

參數:


  • str: It is System.String type parameter which can contain single character or NULL.
  • result: This is an uninitialized parameter which is used to store the Unicode character equivalent when the conversion succeeded, or an undefined value if the conversion failed. The type of this parameter is System.Char.

返回類型:如果成功轉換了字符串,則該方法返回True,否則返回False。因此,此方法的類型為System.Boolean。

注意:當string為NULL或Length等於1時,轉換將失敗。示例1:下麵的程序演示了Char.TryParse()方法的使用。

// C# program to illustrate the 
// Char.TryParse () Method 
using System; 
  
 class GFG { 
  
    // Main Method 
    static public void Main() 
    { 
  
        // Declaration of data type 
        bool result; 
        Char value; 
  
        // Input Capital letter A 
        result = Char.TryParse("A", out value); 
  
        // Display boolean type result 
        Console.WriteLine(result); 
        Console.WriteLine(value.ToString()); 
  
        // Input Capital letter Z 
        result = Char.TryParse("Z", out value); 
  
        // Display boolean type result 
        Console.WriteLine(result); 
        Console.WriteLine(value.ToString()); 
  
        // Input Symbol letter 
        result = Char.TryParse("$", out value); 
  
        // Display boolean type result 
        Console.WriteLine(result); 
        Console.WriteLine(value.ToString()); 
  
        // Input number 
        result = Char.TryParse("100", out value); 
  
        // Display boolean type result 
        Console.WriteLine(result); 
        Console.WriteLine(value.ToString()); 
  
        // Input small letter z 
        result = Char.TryParse("z", out value); 
  
        // Display boolean type result 
        Console.WriteLine(result); 
        Console.WriteLine(value.ToString()); 
    } 
}
輸出:
True
A
True
Z
True
$
False

True
z

範例2:下麵的程序演示了Char.TryParse()方法的使用,其中輸入不是單個字符,而是以符號開頭。

// C# program to illustrate the 
// Char.TryParse () Method 
using System; 
  
class GFG { 
  
    // Main Method 
    static public void Main() 
    { 
  
        // Declaration of data type 
        bool result; 
        Char value; 
  
        // Input is  String return false 
        result = Char.TryParse("GeeksforGeeks", out value); 
  
        // Display boolean type result 
        Console.WriteLine(result); 
        Console.WriteLine(value.ToString()); 
  
        // Input letter start with symbol  < 
        result = Char.TryParse("<N", out value); 
  
        // Display boolean type result 
        Console.WriteLine(result); 
        Console.WriteLine(value.ToString()); 
    } 
}
輸出:
False

False


相關用法


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