在 C# 中,String .Replace 不会替换丹麦字符
In C#, String .Replace wont replace danish chars
所以我有包含丹麦语字符 (æ) 的字符串,比如:
string textString = "tæst";
string newString = "";
出于某种原因
newString = textString .Replace("æ", "e");
没有正确替换,结果是 newString = "tæst"
,而它应该是 newString = "test"
。
但是,并不总是!
我已经在多台服务器上进行了测试,在一些服务器上这被正确返回为 "test"
在其他服务器上这是 "tæst"
。
我在想,也许字符串没有被识别为 utf8 字符串,也许应该被强制识别为 utf8。猜猜看,你有 idea/guess 吗?
谢谢
编辑。是的,没有正确阅读问题。 :(
上面的Rbm是正确的。 new 不是有效名称。此代码有效。
static void Main(string[] args)
{
string text = "tæst";
string s = string.Empty;
s = text.Replace("æ", "e");
Console.WriteLine(s);
Console.ReadKey();
}
大多数 Unicode 字符都有多个看起来非常相似的版本。例如:11①⑴
var s = "æӕ".Replace("æ", "ae"); // s = "aeæ"
var v = "æӕ".Select(c => (int)c).ToArray(); // { 230, 1237 }
我认为预料到意外情况(尤其是涉及用户输入时)是一种很好的做法
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);
这里有一些不相关的Falsehoods Programmers Believe
所以我有包含丹麦语字符 (æ) 的字符串,比如:
string textString = "tæst";
string newString = "";
出于某种原因
newString = textString .Replace("æ", "e");
没有正确替换,结果是 newString = "tæst"
,而它应该是 newString = "test"
。
但是,并不总是!
我已经在多台服务器上进行了测试,在一些服务器上这被正确返回为 "test"
在其他服务器上这是 "tæst"
。
我在想,也许字符串没有被识别为 utf8 字符串,也许应该被强制识别为 utf8。猜猜看,你有 idea/guess 吗?
谢谢
编辑。是的,没有正确阅读问题。 :(
上面的Rbm是正确的。 new 不是有效名称。此代码有效。
static void Main(string[] args)
{
string text = "tæst";
string s = string.Empty;
s = text.Replace("æ", "e");
Console.WriteLine(s);
Console.ReadKey();
}
大多数 Unicode 字符都有多个看起来非常相似的版本。例如:11①⑴
var s = "æӕ".Replace("æ", "ae"); // s = "aeæ"
var v = "æӕ".Select(c => (int)c).ToArray(); // { 230, 1237 }
我认为预料到意外情况(尤其是涉及用户输入时)是一种很好的做法
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);
这里有一些不相关的Falsehoods Programmers Believe