运行此段代码
class Program
{
static void Main(string[] args)
{
// .NET Core 3.1
string s = "Hello\r\nworld!";
int idx = s.IndexOf("\n");
Console.WriteLine(idx);
}
}
返回结果为 6
运行同样代码
class Program
{
static void Main(string[] args)
{
// .NET Core 3.1
string s = "Hello\r\nworld!";
int idx = s.IndexOf("\n");
Console.WriteLine(idx);
}
}
返回结果为 -1
2019年5月, windows 做了一个补丁升级,让后续的 .NET 全球化API 由原来的 NLS 切换到了 ICU 模式,这就是在后续的 .NET5 表现不一致的根源,如果你想退回到 NLS,需要做如下配置。
<ItemGroup>
<RuntimeHostConfigurationOption Include="System.Globalization.UseNls" Value="true" />
</ItemGroup>
{
"runtimeOptions": {
"configProperties": {
"System.Globalization.UseNls": true
}
}
}
你可以使用 StringComparison.Ordinal 来指定字符串比较规则
string s = "Hello\r\nworld!";
int idx = s.IndexOf("\n",StringComparison.Ordinal);
Console.WriteLine(idx);
输出结果为 6
string s = "Hello\r\nworld!";
var comparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison));
foreach (var item in comparisons)
{
Console.WriteLine($"{item}: {s.IndexOf("\n", item)}");
}
结果
踩坑记录之 -- String.IndexOf 在 .Net5 和 .Netcore3 中返回值不一样
原文:https://www.cnblogs.com/Alicia-meng/p/15009467.html