1

我不知道为什么 EndsWith 返回错误。

我有 C# 代码:

string heading = "yakobusho";
bool test = (heading == "yakobusho");
bool back = heading.EndsWith("​sho");
bool front = heading.StartsWith("yak");
bool other = "yakobusho".EndsWith("sho");
Debug.WriteLine("heading = " + heading);
Debug.WriteLine("test = " + test.ToString());
Debug.WriteLine("back = " + back.ToString());
Debug.WriteLine("front = " + front.ToString());
Debug.WriteLine("other = " + other.ToString());

输出是:

heading = yakobusho
test = True
back = False
front = True
other = True

EndsWith 发生了什么?

4

3 回答 3

4

这在“sho”字符串之前包含一个不可见的字符:

bool back = heading.EndsWith("​sho");

更正后的行:

bool back = heading.EndsWith("sho");
于 2019-03-07T14:35:55.327 回答
1

第三行中的"​sho"字符串以零长度空格开头。"​sho".Length返回 4,同时((int)"​sho"[0])返回 8203,即零长度空间的 Unicode 值。

您可以使用其十六进制代码将其键入字符串,例如:

"\x200Bsho"

令人讨厌的是,该字符不被视为空格,因此无法使用String.Trim().

于 2019-03-07T14:42:47.943 回答
0

在您的EndsWith论点中有一个特殊字符。

从这段代码可以看出:

  class Program
  {
    static void Main(string[] args)
    {
      string heading = "yakobusho";

      string yourText = "​sho";
      bool back = heading.EndsWith(yourText);

      Debug.WriteLine("back = " + back.ToString());
      Debug.WriteLine("yourText length = " + yourText.Length);

      string newText = "sho";
      bool backNew = heading.EndsWith(newText);

      Debug.WriteLine("backNew = " + backNew.ToString());
      Debug.WriteLine("newText length = " + newText.Length);

    }
  }

输出:

back = False
yourText length = 4
backNew = True
newText length = 3

的长度yourText为 4,因此该字符串中有一些隐藏字符。

希望这可以帮助。

于 2019-03-07T14:46:15.780 回答