我想把一个字符串放进一个字节数组中,但是这个字符串可能太大而无法容纳。当它太大时,我想尽可能多地将字符串放入数组中。有没有一种有效的方法可以找出有多少个字符能够适应?
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);
}
高效的方法是找出每个字符需要多少字节(悲观情况下)
Encoding.GetMaxByteCount(1);
然后将您的字符串大小除以结果,然后使用该数量的字符进行转换
public virtual int Encoding.GetBytes (
string s,
int charIndex,
int charCount,
byte[] bytes,
int byteIndex
)
如果你想使用更少的内存,请使用
Encoding.GetByteCount(string);
但那是一种更慢的方法。
GetByteCount
的方法,它可以接受字符串或char[]。如果您传入1个字符,它将告诉您在使用的任何编码中需要多少字节来表示该1个字符。GetMaxByteCount
更快,但它进行最坏情况计算,可能返回比实际需要的更高的数字。