//按位元組截取字串
static public string getCountStr2(string str,int count)
{
byte [] bwrite=Encoding.GetEncoding("GB2312").GetBytes(str.ToCharArray());
if(bwrite.Length>=count)
return Encoding.Default.GetString( bwrite,0,count-3);
else return Encoding.Default.GetString(bwrite);
}
一個 C# 字串最終轉化為多長的位元組, 取決於使用的編碼
string s = "china 中華人民共和國";
int l = 0;
byte[] b1 = System.Text.Encoding.Default.GetBytes(s);
l = b1.Length;//20
byte[] b2 = System.Text.Encoding.UTF8.GetBytes(s);
l = b2.Length;//27
byte[] b3 = System.Text.Encoding.Unicode.GetBytes(s);
l = b2.Length;//26
varchar(255):Varchar類型,單位是位元組的,一個中文字元兩個位元組,所以varchar(255),儲存127個漢字和1個英語字元(除於2有餘數)。
轉換為位元組數組
byte[] by=System.Encoding.GetEncoding("GB2312").GetBytes(somestring);
int len=by.Length;
c#判斷輸入的字串的位元組長度
using System.Text;
public partial class zijie : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string pp = getCountStr2("ffff",2);
string mm = getCountStr2("敏敏",2);
}
/// <summary>
/// 判斷位元組的長度
/// </summary>
/// <param name="str">要判斷的字串</param>
/// <param name="count">要顯示的長度</param>
/// <returns>返回截取的字串</returns>
static public string getCountStr2(string str, int count)
{
byte[] bwrite = Encoding.GetEncoding("GB2312").GetBytes(str.ToCharArray());
if (bwrite.Length >= count)
return Encoding.Default.GetString(bwrite, 0, count - 0);
else return Encoding.Default.GetString(bwrite);
}
}
指令碼判段輸入的位元組長度
<head runat="server">
<title>無標題頁</title>
<script language="javascript" type="text/javascript">
function checkName(){
String.prototype.Trim = function() //給string增加個Trim()方法
{
return this.replace(/(^/s*)|(/s*$)/g, "");
}
String.prototype.LTrim = function() //給string增加個LTrim()方法,去左邊的空格
{
return this.replace(/(^/s*)/g, "");
}
String.prototype.RTrim = function() // 給string增加個RTrim()方法,去右邊的空格
{
return this.replace(/(/s*$)/g, "");
}
String.prototype.len = function() // 給string增加個len ()方法,計算string的位元組數
{
return this.replace(/[^/x00-/xff]/g, "xx").length;
}
var obj=document.getElementById("txtContent").value; //取得textbox裡的資料
debugger;
var count=obj.Trim().len();
if(count>80)
{
}
alert(count); //去點空格後計算位元組數
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtContent" Text="" runat="server"></asp:TextBox>
<asp:Button ID="ddd" runat="server" Text="fff" OnClientClick="return checkName()" OnClick="ddd_Click"/>
</div>
</form>
</body>
</html>