Before, because of the need to add IM system to the game project, when there was a character limit. (judging the length on the client side)
For the first time, I wanted to use the Character Limit component in NGUI's Input, but I found that the character length it judged was not divided into full-width and half-width.
Later, when using methods such as System.Text.Encoding.BigEndianUnicode to judge, it was found that the character lengths judged by Unity on different platforms are not the same.
Then I thought of using this method to determine the character length
/// <summary>
/// 判断字符长度
/// </summary>
/// <param name="mString"></param>
/// <returns></returns>
public int CalculatePlaces(string mString)
{
int _placesNum = 0; //统计字节位数
char[] _charArray = mString.ToCharArray();
for (int i = 0; i < _charArray.Length; i++)
{
char _eachChar = _charArray[i];
if (_eachChar >= 0x4e00 && _eachChar <= 0x9fa5) //判断中文字符
_placesNum += 2;
else if (_eachChar >= 0x0000 && _eachChar <= 0x00ff) //已2个字节判断
_placesNum += 1;
}
return _placesNum;
}
Similarly, after judging the character length, you can correspondingly intercept fixed-length characters.
/// <summary>
/// 截取字符
/// </summary>
/// <param name="_mString">字符</param>
/// <param name="_mLenght">长度</param>
/// <returns>定长度的字符</returns>
public string InterceptPlaces(string _mString,int _mLenght)
{
int _placesNum = 0;
char[] _charArray = _mString.ToCharArray();
string _charReturn = string.Empty;
for (int i = 0; i < _charArray.Length; i++)
{
if (_placesNum < _mLenght)
{
char _eachChar = _charArray[i];
if (_eachChar >= 0x4e00 && _eachChar <= 0x9fa5) //判断中文字符
_placesNum += 2;
else if (_eachChar >= 0x0000 && _eachChar <= 0x00ff) //已2个字节判断
_placesNum += 1;
_charReturn += _eachChar.ToString();
}
else if (_placesNum >= _mLenght)
{
break;
}
}
return _charReturn.ToString();
}