如何计算字符的长度和截取字符(小节)

如何计算字符的长度和截取字符(小节)

在此之前,有很多问题问如何判断输入的字符的长度,一般情况很多的人都说一个一个的字取判断,还有全角判断,两种方法:
一:
Public Function GetStringLengthB(ByVal checkString As String) As Integer

        Dim firstB As String                 
        Dim asc As Integer                 
        Dim i As Integer                    
        Dim count As Integer                
        Dim stringLength As Integer         
        Dim strKana As String

        strKana = "アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲンァィゥェォャュョ、。「」゙゚"
        
        If Microsoft.VisualBasic.Trim(checkString) = "" Then
            Return 0
        End If

        stringLength = checkString.Length
        count = 0

        For i = 1 To stringLength
            firstB = Microsoft.VisualBasic.Mid(checkString, i, 1)
            asc = Microsoft.VisualBasic.AscW(firstB)

             If asc < 0 Or asc > 255 Then

                If strKana.IndexOf(firstB) = -1 Then
                    count = count + 2
                Else
                    count = count + 1
                End If
            Else
                count = count + 1
            End If
        Next

        Return count
    End Function


二:
    Private Function GetLength(ByVal str As String) As Integer
        Dim encodingData() As Byte

        encodingData = System.Text.Encoding.Default.GetBytes(str)
        Return encodingData.Length
    End Function


对于字符的截取那就可以采用第二种方法,是以位截取,不是以个数截取。
Private Function GetLength(ByVal str As String,Byval length as string) As string
     Dim encodingData() As Byte

        encodingData = System.Text.Encoding.Default.GetBytes(str)
       If length < encodingData.Length Then
            Return System.Text.Encoding.Default.GetString(encodingData, 0, length )
        Else
            Return str 
        End If

 End Function

你可能感兴趣的:(计算)