【问题标题】:empty string has a length of 1空字符串的长度为 1
【发布时间】:2018-07-22 22:36:41
【问题描述】:

我有一个与_ 连接的名称数组,例如:string[] samples = ["Test_test","Test2_blah", "Test3_"]

在我的代码中的某个时刻,我想尝试验证 _ 之后的值,以检查它是否为空或 null,如果是,则将其从数组中删除,如下所示:

string[] splitSample= samples[2].Split(new char[] { '_' }, 2);

if(!string.IsNullOrWhiteSpace(splitSample[1]))

我遇到的问题是splitSample[1]"",当我检查字符串的长度时它是 1,而不是 0,但在 Visual Studio 2017 中它显示空引号。有没有办法真正看到不可见的价值或实际发生的事情?

编辑: 这是我检查数组值时立即窗口的图片

【问题讨论】:

  • 如果存在splitSample[1],则字符串的长度为2,而不是1。
  • 如果我遗漏了一些明显的东西,请原谅我,但是当你可以单独使用 _ 时,为什么要 new char[] {'_'}
  • @JamesHughes:没有超载可以接受。
  • @LasseVågsætherKarlsen 我收到从字符串到整数的转换错误
  • 你能发布一个完整的例子来展示你所看到的吗?当我尝试重现它时,splitSample[1].Length 是零,正如您所期望的那样。

标签: c# unicode character-encoding


【解决方案1】:

根据它们的呈现方式,某些 Unicode 字符在表示时可能是不可见的(例如,"")(例如,"\u200C""\u2063",并查看this answer 了解更多信息)。

现在,您的字符串有一个长度 (>0),您想知道它实际代表什么。有很多方法可以实现这一点,其中之一是将字符串转换为十六进制。以下是使用上述 Unicode 字符的示例:

static void Main(string[] args)
{
    string invisibleChar = "\u200C";
    string[] samples = { "Test_test", "Test2_blah", "Test3_" + invisibleChar };
    string[] splitSample = samples[2].Split(new char[] { '_' }, 2);

    // Prints "Test3_" (or "Test3_?" if you use Console.Write).
    Debug.Print(samples[2]);
    Debug.Print(splitSample.Length.ToString());     // 2

    if (!string.IsNullOrWhiteSpace(splitSample[1]))
    {
        Debug.Print(splitSample[1].Length.ToString());    // 1
        // Prints "" (or "?" in Console).
        Debug.Print(splitSample[1]);

        var hex = string.Join("", splitSample[1].Select(c => ((int)c).ToString("X2")));
        // Prints "200C"
        Debug.Print(hex);
    }

    Console.ReadLine();
}

请注意,由于您使用的是 !string.IsNullOrWhiteSpace,因此您可能会缺少其他 Unicode 字符(例如,"\u00A0"),因为它们被视为空格。所以,你应该问问自己是否也要检查这些。

希望对您有所帮助。

【讨论】:

  • 感谢您提供如此丰富的信息。我检查了Flickr_ 之后的值,十六进制最终是FE0E
  • 嗯,很高兴我能提供帮助。您还可以在此Wikipedia article 中获取有关此类字符的更多信息。
猜你喜欢
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2015-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多