欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#截取中英文混合指定长度字符串实例

程序员文章站 2024-02-22 15:55:58
复制代码 代码如下:using system.text.regularexpressions;using system.text; /// ...

复制代码 代码如下:

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();
}