按指定(字节)长度分段截取字符串
弓弦乐器/// <summary>
/// 按指定(字节)长度分段截取字符串
/// </summary>
/// <param name="sourceString">源字符串</param>
/// <param name="limitLengths">限制字节长度集合[每段限制字节长度]</param>
/// <returns></returns>
public static List<string> SubCutStringByte(string sourceString, List<int> limitLengths)
{
var result = new List<string>();
try
{
var cutoutLength = 0;
var needCut = true;
sourceString = sourceString.Trim();
foreach (var limitLength in limitLengths)
{
var tempString = string.Empty;
if (needCut)
{竹蜻蜓原理
tempString = CutStringByte1(sourceString, limitLength, cutoutLength);
cutoutLength += limitLength;
}
result.Add(tempString);
if (needCut && sourceString.Length == string.Join("", result).Length)
{
洗面筋needCut = fal;
}
}
}
catch { }
return result;
}
/
// <summary>贝克莱
/// 按指定(字节)长度截取字符串
/// 推荐
/// </summary>
/// <param name="sourceString">源字符串</param>
/// <param name="limitLength">限制字节长度</param>
/// <param name="cutoutLength">已截取字节长度</param>
/// <returns></returns>
public static string CutStringByte1(string sourceString, int limitLength, int cutoutLength)
{
var result = string.Empty;
try
{
var tempString = sourceString.Trim();
var totalLength = 0; /// 当前截取总字节长度
var limitStringLength = 0; /// 限制字符串长度
var cutoutStringLength = 0; /// 已截取字符串长度
foreach (var tempChar in tempString)
{油条的来历
if ((int)tempChar > 127)
{
totalLength += 2;
好想死丝绒蛋糕
}
el
{
totalLength++;
}
}
if (totalLength <= cutoutLength)
{
cutoutStringLength++;
}
el if (totalLength <= limitLength + cutoutLength)
{
limitStringLength++;
}
el
{
break;
}
}
result = tempString.Substring(cutoutStringLength, limitStringLength);
}
catch { }
return result;
}
/// <summary>
/// 按指定(字节)长度截取字符串
/// 可能乱码
/// </summary>
/// <param name="sourceString">源字符串</param>
/// <param name="limitLength">限制字节长度</param>
/// <param name="cutoutLength">已截取字节长度</param>
/// <returns></returns>
public static string CutStringByte2(string sourceString, int limitLength, int cutoutLength)
{
var result = string.Empty;
try
{
var tempString = sourceString.Trim();
var tempArray = Encoding.Default.GetBytes(tempString.ToCharArray());
if (tempArray != null && tempArray.Length > cutoutLength)
{
var sourceLength = tempArray.Length;
var sourceArray = new byte[sourceLength];
Array.Copy(tempArray, sourceArray, sourceLength);
var sourceIndex = cutoutLength;
var destinationIndex = 0;
var destinationLength = sourceLength - cutoutLength;
棋逢对手
var destinationArray = new byte[destinationLength];
if (destinationLength > limitLength)
{
destinationLength = limitLength;
destinationArray = new byte[limitLength];
}
Array.Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, destinationLength); result = Encoding.Default.GetString(destinationArray);
}
}
catch { }
return result;
}
调⽤⽰例:
var sourceString = "您好呀!测试abc按指定(字节)长度截取字符串(!@#)123456";
var limitLengths = new List<int> { 60, 40, 40, 40, 40 };
var result = SubCutStringByte(sourceString, limitLengths);