VB.Net計算含日文的字串長度
以前的代碼找不到了只能自己寫一下了(找到了別人的代碼覺得有點麻煩,沒用)
String.prototype.isBytes = function() {
var cArr = this.match(/[^\x00-\xff|\uff61-\uff9f]/ig);
return (cArr==null ? true : false);}
上面這段代碼是我在JAVA項目裡找的,開始沒看明白
朋友老紀這時發給我一段
public static boolean checkAscii(char ch) {
// Ascii文字かどうか判斷し、返り値とする
return ch >= 0x0000 && ch <= 0x007f;
}
public static boolean checkHANKAKU_KANA(char ch) {
// 半形カタカナかどうか判斷し、返り値とする。
return 0xff61 <= ch && ch <= 0xff9f;
}
這時才知道[^\x00-\xff|\uff61-\uff9f]這個Regex是匹配英文字元和半形日文之外的字元的
注意裡面的這個符號^取反的意思[\x00-\xff|\uff61-\uff9f]裡面沒有沒^就是匹配英文字元和半形日文
加上這個^就是匹配英文字元和半形日文之外的字元
下面這個是我寫的VB.NET的方法計算字串的長度
Public Function GetStringLength(ByVal data As String) As Integer
Dim i As Integer = 0
Dim len As Integer = 0
Dim cc As String = ""
Dim charRegex As New Regex("[\x00-\xff|\uff61-\uff9f]")
For i = 0 To data.Length - 1
文字の取得を行う
cc = data.Substring(i, 1)
If charRegex.IsMatch(cc) Then
len = len + 1
Else
len = len + 2
End If
Next i
Return len
End Function
這樣就可以計算出字串的長度了(有不對的地方請指出)
後來朋友又發給我了一個段代碼,如下
Public Function GetByte(ByVal p_s) As Integer
Dim bySource() As Byte
Dim byEncoded() As Byte
Dim destEncoding As Encoding '更多.net源碼和執行個體,來自樂博網 www.lob.cn
文字列をバイト配列に変換
bySource = Encoding.Unicode.GetBytes(p_s)
エンコーディングを取得 (シフトJISコードページ)
destEncoding = destEncoding.GetEncoding("Shift_JIS")
コードページをUnicodeからシフトJISに変換
byEncoded = Encoding.Convert(Encoding.Unicode, destEncoding, bySource)
Return byEncoded.Length
End Function
Public Function ChkByteLength(ByVal p_strVal As String, ByVal p_strParam As String, ByVal p_nMaxLength As Integer, Optional ByVal p_nMinLength As Integer = 0) As Boolean
If p_nMinLength > 0 Then
If GetByte(p_strVal) > p_nMaxLength Or GetByte(p_strVal) < p_nMinLength Then
m_aMsg.Add(GetLine() & clsMessage.GetMessage("E018", p_strParam, CStr(p_nMinLength), CStr(p_nMaxLength)))
Return False
End If
Else
If GetByte(p_strVal) > p_nMaxLength Then
m_aMsg.Add(GetLine() & clsMessage.GetMessage("E009", p_strParam, CStr(p_nMaxLength)))
Return False
End If
End If
Return True
End Function
這兩個方法沒有試,有興趣的可以試試