length of string

One Chinese character should be 2-byte. But if I use Len(cStr), it get the length equals 1. How can I get the byte numbers of a Chinese string?
cchiAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
caraf_gConnect With a Mentor Commented:
Well,

What you could do is investigate the characters one at a time.

In Unicode, the English characters will not use the second byte:

Private Function StringLength(ByVal strTest As String) As Long

Dim bytTest() As Byte
Dim lngCounter As Long
Dim lngTotal As Long

bytTest = strTest

For lngCounter = LBound(bytTest) To UBound(bytTest) Step 2
    If bytTest(lngCounter + 1) = 0 Then
        lngTotal = lngTotal + 1
    Else
        lngTotal = lngTotal + 2
    End If
Next

StringLength = lngTotal

End Function
0
 
caraf_gCommented:
Dim bytLen() As Byte

bytLen = YourChineseString

LenInBytes = UBound(bytLen) - LBound(bytLen)
0
 
GordonpCommented:
Use LenB()

works in exactly the same way as Len() only it returns the byte length rather than the character length.

All the other string manipulation functions also have byte level equivelants

ie
MidB
LeftB,
RightB

see help for more details on these

Hope this helps

Gordon
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
cchiAuthor Commented:
My code is as below :

Dim bytLen() As Byte
bytLen = MyString
LenInBytes = UBound(bytLen) - LBound(bytLen)

When I first put MyString="test1",
the LenInBytes=9.
second, MyStrin=2 Chinese charactors,
the LenInBytes=3.

If I use LenB() instead of Len(),
every character(chinese or english) will be len=2.
0
 
caraf_gCommented:
Ah, pardon.

It should have been
LenInBytes = UBound(bytLen) - LBound(bytLen) + 1

I forgot about LenB... Of course that's easier, thanks GordonP for reminding me.

Apart from that, strings in VB internally are held as unicode, so even English characters occupy two bytes...
0
 
cchiAuthor Commented:
Now every single chinese character and english character become lenght 2.
What I need is for one chinese character legth=2, and one english character length=1.

thanks.
0
 
GordonpCommented:
Unfortunately due to the way VB handles strings, its not possible as far as I know.

VB uses Unicode to handle strings which means every character is stored as 2 bytes.

Sorry cant help more

Gordon
0
 
cchiAuthor Commented:
That's just like what I am doing now,
I just want know if there are any more efficiency  way to solve this problem.
0
All Courses

From novice to tech pro — start learning today.