如何在我的 ASP Net Core 5.0 项目中比较“ß”和“ss”?

Luc*_*key 6 c# asp.net string-comparison asp.net-core-localization

我有一个带有 MVC 配置的 ASP.Net Core 项目。我使用 ASP.Net Core 版本 5.0\n我的母语是德语,因此我们的数据库也充满了德语单词,例如单词“fu\xc3\x9fball”(这意味着足球或足球,具体取决于您来自哪里) 。

\n

正如您所看到的,这个单词有一个 \xc3\x9f。在德语中,这个“\xc3\x9f”基本上相当于“ss”。因此,如果我有字符串“fu\xc3\x9fball”,如果有人也搜索“fussball”,我希望能够找到它。

\n

我知道 ASP.Net Core 具有良好的本地化和全球化选项,但我似乎无法弄清楚这一点。

\n

考虑以下代码:

\n
var currCulture = CultureInfo.CurrentCulture.Name; // = "de-AT"\n\nvar str1 = "fu\xc3\x9fball";\nstr1.StartsWith("fuss"); //returns false\nstr1.StartsWith("fuss", StringComparison.InvariantCulture); //returns false\nString.Equals("\xc3\x9f", "ss", StringComparison.InvariantCulture); //returns false\n\n
Run Code Online (Sandbox Code Playgroud)\n

由于我使用英语语言的 Windows PC,并且我在另一个 Stackoverflow 问题中读到 CultureInfo 依赖于操作系统,因此我决定将以下内容插入到我的Startup.cs-File 中,正如此 Stackoverflow 问题中所建议的那样

\n
var cultureInfo = new CultureInfo("de-AT"); //de-AT for Austria, i tried with de-DE too for germany, but the result was the same\ncultureInfo.NumberFormat.CurrencySymbol = "\xe2\x82\xac";\n\nCultureInfo.DefaultThreadCurrentCulture = cultureInfo;\nCultureInfo.DefaultThreadCurrentUICulture = cultureInfo;\n
Run Code Online (Sandbox Code Playgroud)\n

不幸的是,在我当前的设置下,它总是告诉我在字符串中比较“\xc3\x9f”和“ss”时它们不相同。“\xc3\xa4”和“ae”也是如此,但我需要以相同的方式找到它们。无论输入是“\xc3\xa4”/“ae”还是“\xc3\x9f”/“ss”。

\n

非常感谢我做错的任何想法,我似乎无法让它发挥作用。

\n

预先感谢您并致以最诚挚的问候!

\n

cha*_*dnt 2

Windows 上的 .NET Core 使用操作系统内置的NLS本地化库,而其他操作系统则使用跨平台且符合标准的ICU 库。由于 NLS 和 ICU 在实现上有所不同,这意味着相同的 .NET Core 程序在比较字符串时可能会在不同平台上产生不同的结果。

\n

为了防止这种混乱,从 .NET 5 开始,决定在所有平台上使用 ICU,包括 Windows。但是,由于许多应用程序(包括您的应用程序)都是在 Windows 上编写的,因此假设字符串比较以 NLS 方式工作,因此您需要执行一些操作才能使它们按 ICU 的预期工作

\n

在您的情况下,您可以显式设置CurrentCulture然后确保在字符串比较中显式使用它:

\n
using System.Globalization;\n\nCultureInfo.CurrentCulture = new CultureInfo("de-AT", false);\nConsole.WriteLine($"CurrentCulture is {CultureInfo.CurrentCulture.Name}.");\n\nstring first = "Sie tanzen auf der Stra\xc3\x9fe.";\nstring second = "Sie tanzen auf der Strasse.";\n\nbool b = string.Equals(first, second, StringComparison.CurrentCulture);\nConsole.WriteLine($"The two strings {(b ? "are" : "are not")} equal.");\n\n// CurrentCulture is de-AT.\n// The two strings are equal.\n
Run Code Online (Sandbox Code Playgroud)\n

如果 ICU 给您的应用程序带来太多问题,通过将以下内容放入.csproj您可以恢复到 NLS,但这应该只在您升级代码以与 ICU 一起使用时真正使用:

\n
  <ItemGroup>\n      <RuntimeHostConfigurationOption Include="System.Globalization.UseNls" Value="true" />\n  </ItemGroup>\n
Run Code Online (Sandbox Code Playgroud)\n