2015-11-05 69 views
10
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(德语)。ArgumentOutOfRangeException使用IndexOf与CultureInfo 1031

IndexOf用'strasse'匹配'straße'或'strasse'并返回18作为位置。

删除和替换都没有任何超载设置文化。

如果我删除6个字符使用删除1字符将被留下,如果输入字符串是'strasse'和'straße'将工作。 如果输入字符串是'straße',我删除7个字符,我得到ArgumentOutOfRangeException。

有没有办法安全地删除找到的字符串?任何提供IndexOf最后一个索引的方法?我越来越接近IndexOf,它的本地代码如预期的 - 所以没办法做自己的事...

+0

如何用空字符串替换它? 's = s.Replace(“strasse”,“”);' – dotctor

+0

@dotctor我相信OP在说'string.Replace'不考虑文化,所以“ss”不符合“ß ”。 – juharr

+0

我正在'en-US'上运行,并且遇到了这个问题。事情就是IndexOf的行为不同。 –

回答

5

原生的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。

+0

如果我想匹配'BerlinerStraße'并使用CompareOptions.IgnoreCase,这将失败 - 任何想法为什么? – isHuman

+0

@isHuman我忽略了从'CompareOptions'到'FindNLSStringEx'选项值的转换:你可以看到'options'参数没有被使用。您需要添加从“CompareOptions.IgnoreCase”到“LINGUISTIC_IGNORECASE”或“NORM_IGNORECASE”(由您决定)的转换。 – hvd

+0

是的,现在看到了相同的:)将尝试。 – isHuman