.NET 7.0 中带有非间距字符的 IndexOf 错误?

问题描述 投票:0回答:1

我在 .NET 7 中看到一个奇怪的问题,其中包含字符串 API IndexOf 和 Contains。我正在使用 C#。重现:

("Foo" + (char)1618).Contains("Foo")
返回 true .... yet

("Foo" + (char)1618).IndexOf("Foo")
返回 -1

1618 是一个无间距的 Unicode 字符。

但是,当我像这样在 Unicode 字符前添加一个空格时:

("Foo" + " " + (char)1618).IndexOf("Foo")

它按预期返回 0。

任何帮助将不胜感激。

contains indexof .net-7.0
1个回答
0
投票

string.Contains(string)

此方法执行序数(区分大小写和不区分文化)比较。搜索从该字符串的第一个字符位置开始,一直持续到最后一个字符位置。

string.IndexOf(string)
使用
CurrentCulture
时:

此方法使用当前文化执行单词(区分大小写和区分文化)搜索。搜索从该实例的第一个字符位置开始,一直持续到最后一个字符位置。

提供文化或

StringComparison.CurrentCulture

参数,使它们等价:

Console.WriteLine(("Foo" + (char)1618).Contains("Foo", StringComparison.CurrentCulture)); // False Console.WriteLine(("Foo" + (char)1618).IndexOf("Foo")); // -1

Console.WriteLine(("Foo" + (char)1618).Contains("Foo")); // True Console.WriteLine(("Foo" + (char)1618).IndexOf("Foo", StringComparison.Ordinal)); // 0
还有 

Behavior changes when comparing strings on .NET 5+ article can be useful.

© www.soinside.com 2019 - 2024. All rights reserved.