C# Chinese and English intercept fixed character length
The width of English characters and Chinese characters in C# is different, and Chinese characters are converted when the length is intercepted
/// <summary>
/// 中英文截取固定字符长
/// </summary>
/// <param name="oriStr">原始字符</param>
/// <param name="length">需要长度(英文1个,中文2个)</param>
/// <returns></returns>
public static string GetSubString(string oriStr,int length)
{
string resultStr = string.Empty;
if (string.IsNullOrEmpty(oriStr)) {
return resultStr; }
var encoding = new System.Text.ASCIIEncoding();
int _length = 0;
int realStrLength = 0;
byte[] bytes = encoding.GetBytes(oriStr);
for (int i = 0; i < bytes.Length; i++)
{
// 汉字
if ((int)bytes[i] == 63)
_length += 2;
// 英文
else
_length += 1;
if(_length > length)
{
break;
}
else
{
realStrLength++;
}
}
resultStr = oriStr.Substring(0, realStrLength);
return resultStr;
}