/// <summary>
/// 截取固定长度字符串显示在页面
/// </summary>
/// <param name="str">要截取的字符串</param>
/// <param name="n">要获取的字节个数</param>
/// <returns>返回截取后的字符串</returns>
public static string stringformat(string str, int n)
{
///
///格式化字符串长度,超出部分显示省略号,区分汉字跟字母。汉字2个字节,字母数字一个字节
///
string temp = string.Empty;
if (System.Text.Encoding.Default.GetByteCount(str) <= n)//如果长度比需要的长度n小,返回原字符串
{
return str;
}
else
{
int t = 0;
char[] q = str.ToCharArray();
for (int i = 0; i < q.Length && t < n; i++)
{
if ((int)q[i] >= 0x4E00 && (int)q[i] <= 0x9FA5)//是否汉字
{
if (t == (n-1))
break;
temp += q[i];
t += 2;
}
else
{
temp += q[i];
t++;
}
}
return (temp);
}
}
//C# 获取字符串长度,一个汉字算两个字节
public static int GetLength(string str)
{
if (str.Length == 0)
return 0;
ASCIIEncoding ascii = new ASCIIEncoding();
int tempLen = 0;
byte[] s = ascii.GetBytes(str);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
{
tempLen += 2;
}
else
{
tempLen += 1;
}
}
return tempLen;
}
--sql中获取字符串的字节数
Create function ByteLen(
@S varchar(2000)
) returns int
AS
begin
declare
@subS varchar(2),
@i int, @Len int
select @i = 0, @Len = 0
while @i < Len(@S)
begin
set @i = @i + 1
set @SubS = SubString(@S, @i, 1)
if Ascii(@SubS) > 127
select @Len = @Len + 2
else
select @Len = @Len + 1
end
return @Len
end
Go
select dbo.ByteLen('",wqd和')
//获得字符串的字节数
public static int bytelenght(string str)
{
//byte[] bytestr = System.Text.Encoding.Unicode.GetBytes(str);
byte[] bytestr = System.Text.Encoding.ASCII.GetBytes(str);
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] s = ascii.GetBytes(str);
int j = 0;
for (int i = 0; i < bytestr.GetLength(0); i++)
{
if (i % 2 == 0)
{
j++;
}
else
{
if (bytestr[i] > 0)
{
j++;
}
}
}
return j;
}
#region 获取字符串的固定字节数
public static string GetConstantStr(string str, int len)
{
string strReturn = "";
for (int i = 0; i < str.Length; i++)
{
strReturn += str[i].ToString();
if (GetLength(strReturn) > len)
{
strReturn = strReturn.Remove(i, 1);
break;
}
}
return strReturn;
}
//C# 获取字符串长度,一个汉字算两个字节
public static int GetLength(string str)
{
if (str.Length == 0)
return 0;
ASCIIEncoding ascii = new ASCIIEncoding();
int tempLen = 0;
byte[] s = ascii.GetBytes(str);
for (int i = 0; i < s.Length; i++)
{
if ((int)s[i] == 63)
{
tempLen += 2;
}
else
{
tempLen += 1;
}
}
return tempLen;
}
#endregion
转载于:https://blog.51cto.com/1890589/554423