【问题标题】:How to remove any utf8mb4 characters in string如何删除字符串中的任何 utf8mb4 字符
【发布时间】:2026-02-23 04:35:02
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net utf-8 utf8mb4


    【解决方案1】:

    这应该用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();
    }
    

    【讨论】: