C intercepts an instance of a chinese english mixture specifying the length of a string

  • 2020-05-24 06:04:59
  • OfStack


using System.Text.RegularExpressions;
using System.Text;
/// <summary>
///  String length ( Calculate by byte )
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
static int StrLength(string str)
{
    int len = 0;
    byte[] b;
    for (int i = 0; i < str.Length; i++)
    {
        b = Encoding.Default.GetBytes(str.Substring(i,1));
        if (b.Length > 1)
            len += 2;
        else
            len++;
    }
    return len;
}
/// <summary>
///  Intercepts a string of specified length ( Calculate by byte )
/// </summary>
/// <param name="str"></param>
/// <param name="length"></param>
/// <returns></returns>
static string StrCut(string str, int length)
{
    int len = 0;
    byte[] b;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < str.Length; i++)
    {
        b = Encoding.Default.GetBytes(str.Substring(i, 1));
        if (b.Length > 1)
            len += 2;
        else
            len++;
        if (len >= length)
            break;
        sb.Append(str[i]);
    }
    return sb.ToString();
}


Related articles: