如何在 C# 中將字串初始化為空字串?
要將字串初始化為空列表 -
string myStr = null;
現在,使用內建方法 IsNullOrEmpty() 來檢查列表是否為空 -
if (string.IsNullOrEmpty(myStr)) { Console.WriteLine("String is empty or null!"); }
讓我們看看完整的程式碼 -
示例
using System; namespace Demo { class Program { static void Main(string[] args) { string myStr = null; if (string.IsNullOrEmpty(myStr)) { Console.WriteLine("String is empty or null!"); } Console.ReadKey(); } } }
輸出
String is empty or null!
另一種將字串初始化為空字串的方法,嘗試以下程式碼。我們在此處使用了 string.Empty -
示例
using System; namespace Demo { public class Program { public static void Main(string[] args) { string myStr = string.Empty; if (string.IsNullOrEmpty(myStr)) { Console.WriteLine("String is empty or null!"); } else { Console.WriteLine("String isn't empty or null!"); } } } }
輸出
String is empty or null!
廣告