使用 C# 如何从字符串中删除 utf8mb4 字符(表情符号等),以便结果完全符合 utf8。

大多数解决方案都涉及更改数据库配置,但不幸的是我没有这种可能性。

最佳答案

这应该用 replacementCharacter (甚至可以是 string.Empty )替换代理字符

鉴于 utf8mb4 ,这是一个 MySql 问题。 Here MySql 中 utf8 和 utf8mb4 有区别。不同之处在于 utf8 不支持 4 字节 utf8 序列。通过查看 wiki ,4 字节 utf8 序列是那些 > 0xFFFF,因此在 utf16 中需要两个 char(称为代理对)。此方法删除代理对字符。当发现“耦合”(高 + 低代理对)时,将替换单个 replacementCharacter ,否则将孤立(错误)高或低代理对替换为 replacementCharacte

public static string RemoveSurrogatePairs(string str, string replacementCharacter = "?")
{
    if (str == null)
    {
        return null;
    }

    StringBuilder sb = null;

    for (int i = 0; i < str.Length; i++)
    {
        char ch = str[i];

        if (char.IsSurrogate(ch))
        {
            if (sb == null)
            {
                sb = new StringBuilder(str, 0, i, str.Length);
            }

            sb.Append(replacementCharacter);

            // If there is a high+low surrogate, skip the low surrogate
            if (i + 1 < str.Length && char.IsHighSurrogate(ch) && char.IsLowSurrogate(str[i + 1]))
            {
                i++;
            }
        }
        else if (sb != null)
        {
            sb.Append(ch);
        }
    }

    return sb == null ? str : sb.ToString();
}

关于c# - 如何删除字符串中的任何 utf8mb4 字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30392702/

10-13 07:55
查看更多