Lua determines how a string contains Chinese characters and calculates string width function sharing _lua

Source: Internet
Author: User

First, the method of judging the string containing Chinese characters

Iterate over the array, use String.byte () for each byte, and find that there are more than 127, that is, Chinese characters, you can refer to the following code.

Second, the calculation string width function

Copy Code code as follows:

--Calculate string width

Local str = "Jimmy: Hello, world!"
Local fontsize = 20
Local Leninbyte = #str
Local width = 0

For I=1,leninbyte do
Local curbyte = String.byte (str, i)
Local byteCount = 1;
If Curbyte>0 and curbyte<=127 then
ByteCount = 1
ElseIf curbyte>=192 and curbyte<223 Then
ByteCount = 2
ElseIf curbyte>=224 and curbyte<239 Then
ByteCount = 3
ElseIf curbyte>=240 and curbyte<=247 Then
ByteCount = 4
End

Local char = string.sub (str, I, i+bytecount-1)
i = i + byteCount-1

If ByteCount = 1 Then
width = width + fontsize * 0.5
Else
width = width + fontsize
Print (char)
End
End

Print (total width:). Width

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.