本机 Win32 API 确实公开了找到的字符串的长度。您可以使用 P/Invoke 直接调用FindNLSStringEx
:
static class CompareInfoExtensions
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private static extern int FindNLSStringEx(string lpLocaleName, uint dwFindNLSStringFlags, string lpStringSource, int cchSource, string lpStringValue, int cchValue, out int pcchFound, IntPtr lpVersionInformation, IntPtr lpReserved, int sortHandle);
const uint FIND_FROMSTART = 0x00400000;
public static int IndexOfEx(this CompareInfo compareInfo, string source, string value, int startIndex, int count, CompareOptions options, out int length)
{
// Argument validation omitted for brevity
return FindNLSStringEx(compareInfo.Name, FIND_FROMSTART, source, source.Length, value, value.Length, out length, IntPtr.Zero, IntPtr.Zero, 0);
}
}
static class Program
{
static void Main()
{
var s = "<<Gewerbegebiet Waldstraße>>";
//var s = "<<Gewerbegebiet Waldstrasse>>";
int length;
int start = new CultureInfo("de-DE").CompareInfo.IndexOfEx(s, "strasse", 0, s.Length, CompareOptions.None, out length);
Console.WriteLine(s.Substring(0, start) + s.Substring(start + length));
}
}
我没有看到纯粹使用 BCL 的方法。