一般計算字串長度,有下列幾種:
1.計算字元數,不管中文字,英文字都算一個字元
2.計算Byte數,中文字算2個byte,英文字算1個byte
舉例:
字串為:"我是puma"
1.計算字元數:中文字(2),英文字(4),總共(6)
2.計算Byte數:中文字(4),英文字(4),總共(8)
程式語法
C#
string str = "我是puma"; //一般的字中長度計算,中文字(2),英文字(4),總共(6) Response.Write(str.Length.ToString()); //利用Byte單位來計算字串長度,中文字(4),英文字(4),總共(8) Response.Write(System.Text.Encoding.Default.GetBytes(str).Length);
VB.Net
Dim str As String = "我是puma" '一般的字中長度計算,中文字(2),英文字(4),總共(6) Response.Write(str.Length.ToString()) '利用Byte單位來計算字串長度,中文字(4),英文字(4),總共(8) Response.Write(System.Text.Encoding.Default.GetBytes(str).Length)
Javascript(小舖Bryan(不來ㄣ)提供)
<script type="text/javascript"> //string.Blength() 傳回字串的byte長度 String.prototype.Blength = function() { var arr = this.match(/[^\x00-\xff]/ig); return arr == null ? this.length : this.length + arr.length; } var str = "我是puma"; alert("字元數:"+str.length); //中文字(2),英文字(4),總共(6) alert("byte數:"+str.Blength()); //中文字(4),英文字(4),總共(8) </script>
參考網址:http://www.blueshop.com.tw/board/show.asp?subcde=BRD20080805173342PL2&fumcde=FUM20041006152641OLGhttp://www.blueshop.com.tw/board/show.asp?subcde=BRD2005120616462427H&fumcde=FUM20041006161839LRJ&rplcnt=7
# re: 利用Byte單位來計算字串長度的幾種做法(Javascript,C#,VB.Net), Posted by cathy on 2009/1/22 下午 04:34 回覆
受用囉!! 謝謝~ ^^