在 C# 中檢查一個字串是否為空或 null
Muhammad Maisam Abbas
2024年2月16日
Csharp
Csharp String
本教程將討論在 C# 中檢查字串是否為空或 null 的方法。
檢查 C# 中的字串是空或者 null
如果我們要檢查其中包含 null 值或""值的字串,可以在 C# 中使用 string.IsNullOrEmpty() 方法。string.IsNullOrEmpty() 方法具有布林返回型別。如果字串為空或 null,則返回 true。請參見以下程式碼示例。
using System;
namespace check_string {
class Program {
static void Main(string[] args) {
string s = null;
if (string.IsNullOrEmpty(s)) {
Console.WriteLine("String is either null or empty");
}
}
}
}
輸出:
String is either null or empty
在上面的程式碼中,我們將 null 值分配給了字串變數 s,並使用 C# 中的 string.IsNullOrEmpty() 方法檢查了該值是空還是 null。
在 C# 中檢查一個字串是否為空
在上一節中,我們檢查 null 值和 "" 值的組合。如果要單獨檢查字串是否為 null,則可以使用 == 比較運算子。請參見以下程式碼示例。
using System;
namespace check_string {
class Program {
static void Main(string[] args) {
string s = null;
if (s == null) {
Console.WriteLine("String is null");
}
}
}
}
輸出:
String is null
在上面的程式碼中,我們使用 C# 中的 == 比較運算子檢查字串變數 s 是否為 null。
在 C# 中檢查一個字串變數是否是空
與前面的示例一樣,我們還可以使用 C# 中的 string.Empty 欄位單獨檢查字串是否為空。string.Empty 欄位代表 C# 中的空白。請參見以下程式碼示例。
using System;
namespace check_string {
class Program {
static void Main(string[] args) {
string s = "";
if (s == string.Empty) {
Console.WriteLine("String is empty");
}
}
}
}
輸出:
String is empty
在上面的程式碼中,我們使用 C# 中的 string.Empty 欄位檢查字串是否為空。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn