1、方法1
创新互联公司2013年至今,先为城区等服务建站,城区等地企业,进行企业商务咨询服务。为城区企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
VB6中提供了LenB函数用于字符串中的字节数据。如同在双字节字符集语言中一样,LenB返回的是用于代表字符串的字节数,而不是返回字符串中字符的数量。如为用户自定义类型,LenB返回在内存中的大小。
LenB)
对要处理的字符串Str1,必须先使用StrConv函数把ANSI格式的Byte数组转换为字符串,否则直接使用LenB函数得到的结果比实际结果大。
2、方法2
这里自定义了一个子函数CLen来计算汉字字符串的实际长度。同时还能判定字符串中汉字的实际个数。
Function
CLen
as
Integer
Static
HzNum
as
Integer
L
=
len
For
n=1
to
L
If
Asc)<0
Then
HzNum
=
HzNum
+
1
Next
n
Clen
=
L
+
HzNum
End
Function
CLen函数中的静态变量HzNum返回字符串中实际汉字的数目。
字符编码转换吗?
1.字符与gb2312(gbk的子集):
Public Function GBKEncode(ByVal sInput As String) As String
Dim ret_GBKEncode As String = ""
Dim i As Integer
Dim startIndex As Integer = 0
Dim endIndex As Integer
Dim x() As Byte = System.Text.Encoding.Default.GetBytes(sInput) '字符以及字符串在vb2008中都是以unicode编码存储的
endIndex = x.Length - 1
For i = startIndex To endIndex
ret_GBKEncode = "%" Hex(x(i))
Next
Return ret_GBKEncode
End Function
'GBK解码
Public Function GBKDecode(ByVal sInput As String) As String
sInput = sInput.Replace("%", "")
Dim ret_GBKDecode As String = ""
Dim sLen As Integer = sInput.Length
Dim n As Integer = sLen \ 2
Dim sBytes(0 To n - 1) As Byte
'转化为字节码
For i As Integer = 1 To n
sBytes(i - 1) = CByte("H" sInput.Substring(2 * i - 2, 2))
Next
'将字节码转化为字符串
ret_GBKDecode = System.Text.Encoding.Default.GetString(sBytes)
Return ret_GBKDecode
End Function
2.Unicode字符串为UTF-8
Imports System.Text
Public Function StringAsUtf8Bytes(ByVal strData As String) As Byte()
Dim bytes() As Byte
bytes = Encoding.UTF8.GetBytes(strData)
Return bytes
End Function
'这里可以类推出好几种。
GB2312是GBK编码的子集,使用GBK编码函数即可
'GBK编码(结果以百分号%进行分隔)
Public Function GBKEncode(ByVal sInput As String) As String
Dim ret_GBKEncode As String = ""
Dim i As Integer
Dim startIndex As Integer = 0
Dim endIndex As Integer
Dim x() As Byte = System.Text.Encoding.Default.GetBytes(sInput) '字符以及字符串在vb2008中都是以unicode编码存储的
endIndex = x.Length - 1
For i = startIndex To endIndex
ret_GBKEncode = "%" Hex(x(i))
Next
Return ret_GBKEncode
End Function
'GBK解码
Public Function GBKDecode(ByVal sInput As String) As String
sInput = sInput.Replace("%", "")
Dim ret_GBKDecode As String = ""
Dim sLen As Integer = sInput.Length
Dim n As Integer = sLen \ 2
Dim sBytes(0 To n - 1) As Byte
'转化为字节码
For i As Integer = 1 To n
sBytes(i - 1) = CByte("H" sInput.Substring(2 * i - 2, 2))
Next
'将字节码转化为字符串
ret_GBKDecode = System.Text.Encoding.Default.GetString(sBytes)
Return ret_GBKDecode
End Function
public string hz2py(string hz) //获得汉字的区位码
{
byte[] sarr = System.Text.Encoding.Default.GetBytes(hz);
int len = sarr.Length;
if (len1)
{
byte[] array = new byte[2];
array = System.Text.Encoding.Default.GetBytes(hz);
int i1 = (short)(array[0] - '\0');
int i2 = (short)(array[1] - '\0');
//unicode解码方式下的汉字码
// array = System.Text.Encoding.Unicode.GetBytes(hz);
// int i1 = (short)(array[0] - '\0');
// int i2 = (short)(array[1] - '\0');
// int t1 = Convert.ToInt32(i1,16);
// int t2 = Convert.ToInt32(i2,16);
一样的还是使用asc函数就好了啊!,n=ASC(“汉”),不过汉字的asc码都是小于0的