C# EndsWith 有时会给出错误结果

标签 c# ends-with

“Cs”.EndsWith(“s”)和“cs”.EndsWith(“s”)给我“假”。

我编写了一个简单的控制台应用程序来呈现问题:

string[] strings = { "s", "As", "Bs", "Cs", "Ds", "Es", "as", "bs", "cs", "ds", "es", "AAs", "ABs", "ACs", "ADs", "AEs" };
foreach (string str in strings)
  Console.WriteLine(str + " ends with 's': " + str.EndsWith("s"));
Console.ReadKey();

结果是这样的:

s ends with 's': True
As ends with 's': True
Bs ends with 's': True
Cs ends with 's': False
Ds ends with 's': True
Es ends with 's': True
as ends with 's': True
bs ends with 's': True
cs ends with 's': False
ds ends with 's': True
es ends with 's': True
AAs ends with 's': True
ABs ends with 's': True
ACs ends with 's': False
ADs ends with 's': True
AEs ends with 's': True

我尝试更改目标框架:(VS2013)

  • 所有 4.x 版本都会产生此错误
  • 在 .NET 3.5、3.0、2.0 上运行良好。

还尝试使用 .NET 6.0 来使用 VS2022 Preview(在两台不同的计算机上),但产生了相同的问题。

在 dotnetfiddle (.NET 4.7.2) 中它运行良好...:-O

你能帮我在哪里寻找解决方案吗? (设置、安装的软件等)

提前致谢。

最佳答案

一般来说,您的情况最简单的方法是告诉字符串比较器它应该使用序数比较,如下所示:

str.EndsWith("s", StringComparison.Ordinal)

正如评论中的人们已经解释的那样,大多数字符串函数都适用于当前的文化,而且似乎是匈牙利语,这就是您得到这些结果的原因。

另一个好处是,顺序比较是迄今为止最快的。

关于C# EndsWith 有时会给出错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68467553/

相关文章:

c# - 如何使用 ZedGraph 库显示多个具有公共(public) X 轴的图形?

Azure 搜索 : Doesn't give correct results with slashes and solutions given for "ends with" doesn't work

Python(2.6.6)for循环中的endswith()

ruby - 如何查看字符串是否以多个字符之一结尾

python - 如何打印从 'startswith' 到 'endswith' 的字符串部分

java - 函数 endsWith 中的 JSTL 错误?

c# - Roslyn 在解决方案的所有项目中查找对方法的所有引用

C# MetroTile 背景色/前色在鼠标进入/离开期间不改变

c# - 如何在我的 View 中单击按钮时从 session ["cart"] 中删除项目?

c# - 在大型 wpf 数据网格中移动/隐藏列的性能问题