【发布时间】:2013-12-27 02:48:09
【问题描述】:
我尝试编写一种文化感知字符串替换方法:
public static string Replace(string text, string oldValue, string newValue)
{
int index = text.IndexOf(oldValue, StringComparison.CurrentCulture);
return index >= 0
? text.Substring(0, index) + newValue + text.Substring(index + oldValue.Length)
: text;
}
但是,它在 Unicode 组合字符上卡住了:
// \u0301 is Combining Acute Accent
Console.WriteLine(Replace("déf", "é", "o")); // 1. CORRECT: dof
Console.WriteLine(Replace("déf", "e\u0301", "o")); // 2. INCORRECT: do
Console.WriteLine(Replace("de\u0301f", "é", "o")); // 3. INCORRECT: dóf
要修复我的代码,我需要知道在第二个示例中,String.IndexOf 仅匹配一个字符 (é),即使它搜索了两个 (e\u0301)。同样,我需要知道在第三个示例中,String.IndexOf 匹配了两个字符(e\u0301),即使它只搜索了一个字符(é)。
如何确定String.IndexOf匹配的子串的实际长度?
注意: 对 text 和 oldValue 执行 Unicode 规范化(如 James Keesey 所建议)将适应组合字符,但连字仍然是一个问题:
Console.WriteLine(Replace("œf", "œ", "i")); // 4. CORRECT: if
Console.WriteLine(Replace("œf", "oe", "i")); // 5. INCORRECT: i
Console.WriteLine(Replace("oef", "œ", "i")); // 6. INCORRECT: ief
【问题讨论】: