LastIndexOf 改善了空白搜尋字串的處理方式

String.LastIndexOf 和相關的 API 現在會於較大字串內搜尋零長度 (或相當於零長度) substring 時傳回正確的值。

變更描述

在 .NET Framework 和 .NET Core 1.0 到 3.1 中,String.LastIndexOf 和相關的 API 可能在呼叫端搜尋零長度 substring 時傳回不正確的值。

Console.WriteLine("Hello".LastIndexOf("")); // prints '4' (incorrect)

ReadOnlySpan<char> span = "Hello";
Console.WriteLine(span.LastIndexOf("")); // prints '0' (incorrect)

從 .NET 5 開始,這些 API 會為 LastIndexOf 傳回正確的值。

Console.WriteLine("Hello".LastIndexOf("")); // prints '5' (correct)

ReadOnlySpan<char> span = "Hello";
Console.WriteLine(span.LastIndexOf("")); // prints '5' (correct)

在這些範例中,5 是正確答案,因為 "Hello".Substring(5)"Hello".AsSpan().Slice(5) 都會產生空白的字串,與尋找的空白 substring 完全相同。

變更原因

這項變更是 .NET 5 在字串處理方面整體錯誤修正的措施之一。 這項變更也能統一我們在 Windows 和非 Windows 平台上的行為。 如需詳細資訊,請參閱 dotnet/runtime#13383 dotnet/runtime##13382

導入的版本

5.0

您不需要採取任何動作。 .NET 5 執行階段會自動提供新的行為。

沒有相容性參數可還原舊版行為。

受影響的 API