在C#中, IsNullOrWhiteSpace() 是一个字符串方法。用于检查指定的字符串是否正确 无效的 或者只包含 空白 角色。如果字符串未被赋值或显式赋值为null,则该字符串将为null。
null
语法:
public static bool IsNullOrWhiteSpace(String str)
说明: 此方法将采用类型为的参数 系统一串 这个方法将返回一个布尔值。如果方法的参数列表为null或 一串空的 ,或仅包含空格字符,然后返回True,否则返回False。
例子:
Input : str = null // initialize by null value String.IsNullOrWhiteSpace(str) Output: True Input : str = " " // initialize by whitespace String.IsNullOrWhiteSpace(str) Output: True
节目: 要演示IsNullOrWhiteSpace()方法的工作原理,请执行以下操作:
// C# program to illustrate // IsNullOrWhiteSpace() Method using System; class Geeks { // Main Method public static void Main( string [] args) { string s1 = null ; // for null value always return true bool b1 = String.IsNullOrWhiteSpace(s1); Console.WriteLine(b1); string s2 = " " ; // for whitespace value always return true bool b2 = String.IsNullOrWhiteSpace(s2); Console.WriteLine(b2); string s4 = " " ; // for new line value return true bool b4 = String.IsNullOrWhiteSpace(s4); Console.WriteLine(b4); string s5 = " " ; // for tab value return true bool b5 = String.IsNullOrWhiteSpace(s5); Console.WriteLine(b5); string s6 = " ; // for carriage Return value return true bool b6 = String.IsNullOrWhiteSpace(s6); Console.WriteLine(b6); string s7 = "GFG" ; // for s7 it return False bool b7 = String.IsNullOrWhiteSpace(s7); Console.WriteLine(b7); } } |
输出:
True True True True True False
注: IsNullOrWhiteSpace()方法的另一个代码如下:
return String.IsNullOrEmpty(str) || str.Trim().Length == 0;
节目: 演示IsNullOrEmpty()方法的替代方法
// C# program to illustrate the // similar code for IsNullOrWhiteSpace() using System; class Geeks { // similar code to // IsNullOrWhiteSpace() public static bool check( string str) { return (String.IsNullOrEmpty(str) || str.Trim().Length == 0) ? true : false ; } // Main Method public static void Main( string [] args) { string s1 = "GeeksforGeeks" ; string s2 = " " ; string s3 = null ; string s4 = " " ; bool b1 = check(s1); bool b2 = check(s2); bool b3 = check(s3); bool b4 = check(s4); // To display result Console.WriteLine(b1); Console.WriteLine(b2); Console.WriteLine(b3); Console.WriteLine(b4); } } |
输出:
False True True True
参考: https://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END