您的位置:首页 > 其它

将汉字字母混合字符串按指定字节截取长度

2010-10-27 15:19 477 查看
分析以下代码,运行结果

string strTmp = "abcdefg某某某";
int i= System.Text.Encoding.Default.GetBytes(strTmp).Length;
int j= strTmp.Length;
以上代码执行完后,i= j=
答:i=13,j=10

class Program
{
static int ascii_len(string str)
{
return str.Length + str.ToCharArray().Count((c) => c > 255);
}
static string ascii_Substring(string str, int len)
{
int a_len = ascii_len(str);
if(a_len<=len)
{
return str;
}
int idx = 0;
int i=0;
while (i < len)
{
i += str[idx] > 255 ? 2 : 1;
idx += 1;
}
if(i>len)
{
idx -= 1;
}
return str.Substring(0, idx);
}

static void Main(string[] args)
{
string a = "z中a国abc";
System.Console.WriteLine(ascii_len(a));
System.Console.WriteLine(ascii_Substring(a, 4));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: