【问题标题】:What's wrong with my usage of String.EndsWith?我对 String.EndsWith 的使用有什么问题?
【发布时间】:2019-03-07 14:30:05
【问题描述】:

我无法弄清楚 EndsWith 为何返回 false。

我有 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 是怎么回事?

【问题讨论】:

  • 将其复制到dotnetfiddle 突出显示"sho" 开头有一个隐藏字符
  • 不同的字符,可能是隐藏字符。 EndsWith()没有错
  • 第三行的"​sho"字符串长度为4个字符

标签: c# asp.net ends-with


【解决方案1】:

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

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

更正后的行:

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

【讨论】:

    【解决方案2】:

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

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

    "\x200Bsho"
    

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

    【讨论】:

      【解决方案3】:

      在您的 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,所以这个字符串中有一些隐藏字符。

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-22
        • 1970-01-01
        • 2018-10-13
        • 2018-11-01
        • 1970-01-01
        相关资源
        最近更新 更多