c# – 使用IndexOf与CultureInfo 1031的ArgumentOutOfRangeExcep
发布时间:2020-12-15 06:32:56 所属栏目:百科 来源:网络整理
导读: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将
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’将工作. 有没有办法安全地删除找到的字符串?提供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的方法. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |