计算字符串长度(关于日文字符)

王朝other·作者佚名  2008-05-30
窄屏简体版  字體: |||超大  

项目要求: 计算一个字符串的长度(对日项目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]这个正则表达式是匹配英文字符和半角日文之外的字符的

注意里面的这个符号^取反的意思[\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

' 文字列をバイト配列に変換

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

这两个方法没有试,有兴趣的可以试试

http://www.cnblogs.com/lost0/archive/2006/11/29/576040.html

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航