c# – 使用IndexOf与CultureInfo 1031的ArgumentOutOfRangeException

c# – 使用IndexOf与CultureInfo 1031的ArgumentOutOfRangeException,第1张

概述string s = "Gewerbegebiet Waldstraße"; //other possible input "Waldstrasse"int iFoundStart = s.IndexOf("strasse", StringComparison.CurrentCulture);if (iFoundStart > -1) s = s.Remove(iFoundStart
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都没有设置文化的重载.

如果我删除6个字符使用Remove 1字符将留下,如果input-string是’strasse’和’straße’将工作.
如果input-string是’straße’,并且我删除7个字符,我得到ArgumentOutOfRangeException.

有没有办法安全地删除找到的字符串?提供IndexOf的最后一个索引的任何方法?我走近IndexOf,它的本机代码在引擎盖下,如预期的 – 所以没有办法做一些自己的事情…

解决方法 本机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,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",s.Length,CompareOptions.None,out length);        Console.Writeline(s.Substring(0,start) + s.Substring(start + length));    }}

我没有看到一种纯粹是BCL的方法.

总结

以上是内存溢出为你收集整理的c# – 使用IndexOf与CultureInfo 1031的ArgumentOutOfRangeException全部内容,希望文章能够帮你解决c# – 使用IndexOf与CultureInfo 1031的ArgumentOutOfRangeException所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1258866.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存