VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > c#编程 >
  • C#教程之C#截取中英文混合指定长度字符串实例

代码如下:

using System.Text.RegularExpressions;
using System.Text;

 

/// <summary>
/// 字符串长度(按字节算)
/// </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>
/// 截取指定长度字符串(按字节算)
/// </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();
}



相关教程