C# String.IsNullOrEmpty() 方法
String.IsNullOrEmpty() 方法是 String 類的 內置 方法,用於檢查字符串是 Null 還是 Empty?如果字符串對象沒有用正確的值初始化,它將被視為 "null string",如果字符串對象被初始化但不包含任何內容,即它被分配了值 (""),它將被視為 "empty string"。
用法:
public static bool IsNullOrEmpty(String str);
該方法使用 "string"/"String" 調用。這裏,"string" 是 "String" 類的別名。
參數:
str
– 表示要檢查的字符串值或字符串對象。
返回值:
bool
– 如果它返回 "True"str
為空或為空,否則返回 "False"。
例:
Input: string str1 = ""; string str2 = null; string str3 = "IncludeHelp"; Function call Console.WriteLine(string.IsNullOrEmpty(str1)); Console.WriteLine(string.IsNullOrEmpty(str2)); Console.WriteLine(string.IsNullOrEmpty(str3)); Output: True True False
使用 String.IsNullOrEmpty() 方法將字符串轉換為字符數組的 C# 示例
範例1:
using System;
class IncludeHelp
{
static void Main()
{
// declaring string variables
string str1 = "";
string str2 = null;
string str3 = "IncludeHelp";
// check whether string is empty/null or not
Console.WriteLine(string.IsNullOrEmpty(str1));
Console.WriteLine(string.IsNullOrEmpty(str2));
Console.WriteLine(string.IsNullOrEmpty(str3));
}
}
輸出
True True False
範例2:
using System;
class IncludeHelp
{
static void Main()
{
// declaring string variable
string str = "IncludeHelp";
// checking whether string is null/empty or not
if(string.IsNullOrEmpty(str))
Console.WriteLine("str is empty or null");
else
Console.WriteLine("str is not empty or null");
//now assigning null to the string
str = null;
// checking whether string is null/empty or not
if(string.IsNullOrEmpty(str))
Console.WriteLine("str is empty or null");
else
Console.WriteLine("str is not empty or null");
}
}
輸出
str is not empty or null str is empty or null
相關用法
- C# String.IsNormalized用法及代碼示例
- C# String.Insert()用法及代碼示例
- C# String.IndexOf()方法用法及代碼示例
- C# String.ToUpperInvariant用法及代碼示例
- C# String.ToLowerInvariant用法及代碼示例
- C# String.ToCharArray()用法及代碼示例
- C# String.Copy()用法及代碼示例
- C# String.Clone()用法及代碼示例
- C# String.Split()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# String.Format()函數用法及代碼示例
- C# String.CopyTo()用法及代碼示例
- C# String.Compare()用法及代碼示例
- C# String.Format()方法用法及代碼示例
- C# StringBuilder.ToString用法及代碼示例
- C# String ToLower()用法及代碼示例
- C# String ToString()用法及代碼示例
- C# String Contains()用法及代碼示例
- C# String ToCharArray()用法及代碼示例
- C# String IndexOf()用法及代碼示例
注:本文由純淨天空篩選整理自 String.IsNullOrEmpty() method with example in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。