VB.net 如何获得中文字符串的长度?

来源:百度知道 编辑:UC知道 时间:2024/05/28 01:50:25
VB.net 2005 中想获取 中文的长度 (其实是日文,不过都一样)

中文是占两格的 但是我获取 Len("中文") 返回值却是 2 而不是4

请问如何让其获得实际长度呢?

而且我需要对混合字符串 如 “AAA-中文” 来进行获得长度(期望值是8,Len实际是6)

请问该用何种函数?
感谢所有回答者。

LenB ,VB.net2005没有这个函数阿

murphylau大侠 LenC那个函数 里面怎么有 Text1.text ?

jyh_jack大侠给了我一份根据 murphylau大侠 的函数改的代码,可以运行。

也很感谢 孤狼剑士 大侠 提供思路。

最接近的代码是murphylau大侠分就给你啦

上面思路是正确的, 用ascw 函数也可以

private function LenC( ps as string ) as Integer

Dim n As Integer
Dim StrLen As Integer

For n = 1 To Len(Text1.Text)
If Ascw(Mid(Text1.Text, n, 1)) >256 Then
StrLen = StrLen + 2
Else
StrLen = StrLen + 1
Next n

return strLen

end function

中文、日文、乱码等字符的ascii码是负数,只有标准的字母、数字、符号的ascii码是正数,你可以根据这个判断,例如:

Private Sub Command1_Click()
Dim n As Integer
Dim StrLen As Integer

For n = 1 To Len(Text1.Text)
If Asc(Mid(Text1.Text, n, 1)) < 0 Then StrLen = StrLen + 2 Else StrLen = StrLen + 1
Next n
MsgBox StrLen
End Sub

使用lenB

LenB("AAA-中文")

Dim int As Integer
int = System.Text.Encoding.Default.GetBytes(TextBox1.Text).Length

LenB(StrConv("AAA-中文", vbFromUnicode))