string.IsNullOrWhiteSpace()能识别全角空格吗
在c#中,判断包含全角空格的字符串是否为空,最直接的方法是使用string.isnullorwhitespace()。该静态方法不仅检查字符串是否为null或空字符串,还会自动跳过所有unicode空白字符,其中就包括全角空格(u+3000)。因此,只要字符串仅由全角空格组成,该方法会返回true,从而将其视为“空”。

using System;
class Program
{
static void Main()
{
string fullWidthSpace = "\u3000";
string normalSpace = " ";
string empty = "";
string nullStr = null;
Console.WriteLine($"IsNullOrWhiteSpace(全角空格): {string.IsNullOrWhiteSpace(fullWidthSpace)}");
Console.WriteLine($"IsNullOrWhiteSpace(普通空格): {string.IsNullOrWhiteSpace(normalSpace)}");
Console.WriteLine($"IsNullOrWhiteSpace(空字符串): {string.IsNullOrWhiteSpace(empty)}");
Console.WriteLine($"IsNullOrWhiteSpace(null): {string.IsNullOrWhiteSpace(nullStr)}");
}
}运行上述代码,控制台将输出四个true。这表明IsNullOrWhiteSpace能够统一处理各种常见的空白情况,无需手动替换或正则匹配。
Trim()配合长度判断是否有效
另一种常见做法是先调用Trim()去除首尾空白,再检查剩余长度。然而,string.Trim()默认只移除ASCII空格(U+0020)及少量其他控制字符,并不包含全角空格。因此,如果直接使用Trim().Length == 0来判断仅含全角空格的字符串,结果会是false,导致误判。

using System;
class Program
{
static void Main()
{
string fullWidthSpace = "\u3000";
string normalSpace = " ";
// 使用默认 Trim
Console.WriteLine($"Default Trim Length (全角): {fullWidthSpace.Trim().Length}");
Console.WriteLine($"Default Trim Length (普通): {normalSpace.Trim().Length}");
// 使用 TrimWithFullWidth 自定义方法
Console.WriteLine($"Custom Trim Length (全角): {TrimWithFullWidth(fullWidthSpace).Length}");
}
static string TrimWithFullWidth(string input)
{
if (input == null) return null;
return input.Trim('\u3000');
}
}为了正确处理全角空格,可以调用Trim(char[] trimChars)重载,显式传入全角空格字符'\u3000'。如代码所示,Trim('\u3000')能有效移除全角空格,使长度为0的判断生效。但需注意,这种方法不如IsNullOrWhiteSpace通用,因为它不处理其他类型的Unicode空白。
仅含全角空格的字符串在IsNullOrEmpty中的表现
如果错误地使用了string.IsNullOrEmpty()来判断全角空格字符串,会得到与预期不符的结果。IsNullOrEmpty仅检查字符串是否为null或零长度(""),它不会识别任何空白字符。因此,一个仅包含全角空格的字符串,其长度大于0,会被判定为“非空”。
using System;
class Program
{
static void Main()
{
string fullWidthSpace = "\u3000";
Console.WriteLine($"IsNullOrEmpty(全角空格): {string.IsNullOrEmpty(fullWidthSpace)}");
Console.WriteLine($"Length of fullWidthSpace: {fullWidthSpace.Length}");
}
}运行结果显示IsNullOrEmpty返回false,且长度为1。这证实了在处理可能包含全角空格的输入时,必须避免使用IsNullOrEmpty,而应选用IsNullOrWhiteSpace或自定义的Trim逻辑。


















