c# - ArgumentOutOfRangeException 使用 IndexOf 和 CultureInfo 1031

标签 c# exception indexof currentculture

string s = "Gewerbegebiet Waldstraße"; //other possible input "Waldstrasse"

int iFoundStart = s.IndexOf("strasse", StringComparison.CurrentCulture);
if (iFoundStart > -1)
    s = s.Remove(iFoundStart, 7);

我正在运行 CultureInfo 1031(德语)。

IndexOf 将“straße”或“strasse”与定义的“strasse”匹配并返回 18 作为位置。

Remove 和 Replace 都不会因为设置文化而过载。

如果我使用删除 1 个字符删除 6 个字符,如果输入字符串是 'strasse' 并且 'straße' 将起作用。 如果输入字符串是“straße”并且我删除了 7 个字符,我会得到 ArgumentOutOfRangeException。

有没有办法安全地删除找到的字符串?提供 IndexOf 的最后索引的任何方法?我更深入地研究了 IndexOf,它是预期的底层原生代码 - 所以无法自己做一些事情......

最佳答案

native 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 来执行此操作的方法。

关于c# - ArgumentOutOfRangeException 使用 IndexOf 和 CultureInfo 1031,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33551888/

相关文章:

javascript - 检测值中非字母数字字符的函数存在语法错误?

c# - "StandardOut has not been redirected or the process hasn' t 尚未开始"After Process.GetProcessById()

c# - 如何以编程方式从 C# 使用 Word 的 "Compare and Merge Documents..."功能?

java - 更新 Apache POI 4.0 后 - 无法识别属性 'http://www.oracle.com/xml/jaxp/properties/entityExpansionLimit'

c# - 当 Unicode 0xFFFD 在字符串中时 IndexOf 匹配 - 错误或功能?

C语言: try to implement IndexOf function

c# - 确定两个类中的所有属性是否相等

c# - 当方法的新实例运行 C# 时,以前的方法仍在将数据写入文本文件

c# - 当有多个服务可用时 WCF 服务无法启动

c++ - 如果满足条件或发生错误