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

2025-05-20 12:26:58
推荐回答(5个)
回答1:

上面思路是正确的, 用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

回答2:

中文、日文、乱码等字符的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

回答3:

遍历每一个字符,看是全角还是半角的。半角的字符总数
+1,全角的字符总数
+2。

参考:
public function getbytelength(byval value as string) as long
dim i as long = 0
for each c as char in value
if (c.tostring().length = system.text.encoding.default.getbytecount(value.tostring())) then
i = i + 1
end if
i = i + 1
next
return i
end function

回答4:

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

回答5:

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