c# - 如何在 C# 中转换为字节时截断字符串?

标签 c# .net arrays string truncate

我想将一个字符串放入一个字节数组中,但该字符串可能太大而放不下。在太大的情况下,我想将尽可能多的字符串放入数组中。有没有一种有效的方法来找出适合多少个字符?

最佳答案

为了将字符串截断为 UTF8 字节数组而不在字符中间拆分,我使用了这个:

static string Truncate(string s, int maxLength) {
    if (Encoding.UTF8.GetByteCount(s) <= maxLength)
        return s;
    var cs = s.ToCharArray();
    int length = 0;
    int i = 0;
    while (i < cs.Length){
        int charSize = 1;
        if (i < (cs.Length - 1) && char.IsSurrogate(cs[i]))
            charSize = 2;
        int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize);
        if ((byteSize + length) <= maxLength){
            i = i + charSize;
            length += byteSize;
        }
        else
            break;
    }
    return s.Substring(0, i);
}

然后可以将返回的字符串安全地传输到长度为 maxLength 的字节数组。

关于c# - 如何在 C# 中转换为字节时截断字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34395/

相关文章:

arrays - Excel - 带有 IF 函数的列表中的模态值

c# - 在 C# 中的 Windows Phone 7 中检索自己的手机号码

java - JNA 中的 Marshal.StructureToPtr Java 等价物

c# - 如何将 ASP.NET 服务器控件传递给函数?

c# - winforms c# 中的静态属性

c# - 使用 DirectorySearcher.FindAll() 时发生内存泄漏

c# - WP 7.1 上的 Restsharp 添加 cookie

c# - mef 中的意外结果

c - 将 C 数组返回到 VB.NET

c 中的条件不满足