在C#中,String .Replace不会替换丹麦字符

Han*_*utz -5 .net c# string str-replace

所以我有一个包含丹麦字符(æ)的字符串,说:

string textString = "tæst"; string newString = "";

由于某种原因

newString = textString .Replace("æ", "e");
Run Code Online (Sandbox Code Playgroud)

未正确替换,newString = "tæst"应按原样生成newString = "test"

但是,并非总是如此

我已经在多台服务器上进行了测试,在某些服务器上可以正确返回,而"test"在其他服务器上则可以"tæst"

我在想,也许该字符串不能被识别为utf8字符串,并且应该被强制识别为utf8。只是一个猜测,您有想法/猜测吗?

谢谢

Sla*_*lai 5

大多数Unicode字符有多个版本,看起来非常相似。例如:1 ???

var s = "æ?".Replace("æ", "ae"); // s = "aeæ"
var v = "æ?".Select(c => (int)c).ToArray(); // { 230, 1237 }
Run Code Online (Sandbox Code Playgroud)

我认为这是一种很好的做法,可以预料到意外情况(尤其是在用户输入方面)

var s = "æ?";
var a = s.ToCharArray(); // or use StringBuilder for non 1 to 1 character replacements

for (int i = 0; i < s.Length; i++)
    if (a[i] > 127)
        switch (a[i]) {
            case 'æ': case '?': 
                a[i] = 'e'; break;
            default: 
                Debug.Print("Unexpected character " + a[i]);
        }

s = new string(a);
Run Code Online (Sandbox Code Playgroud)

这是一些无关的虚假程序员相信