''' <summary>
    ''' 將英數等半形符號,每兩個字元視為一個全形字/長度
    ''' </summary>
    ''' <param name="TheMixedString">混合字串(來源)</param>
    ''' <param name="TheLength">欲取得之字串長度</param>
    ''' <returns>String</returns>
    ''' <remarks></remarks>
    Public Shared Function HalfWay(ByVal TheMixedString As String, ByVal TheLength As Integer) As String
        Try
            If TheMixedString = "" Or TheLength <= 0 Then
                Return "-1"
            Else
                Dim c As Char ''如果是使用 VS2008 則可以直接省略本段,因 VB2008 有方便的型別推論
                Dim sngTotalLength As Single = 0.0
                Dim intPosition As Integer = 0
                For Each c In TheMixedString.ToCharArray
                    ''取自「強力鎯頭 VB BLOG」的內容,
                    ''原本這裡我是以正則式來列舉,後來發現 強力鎯頭 兄的方法比較帥
                    ''所以就直接 copy-paste 過來了:p
                    If Hex(Asc(c)).Length = 2 Then
                        sngTotalLength += 0.5
                    Else
                        sngTotalLength += 1
                    End If

                    ''這段的用意是用來避免讓回傳字串長度超出範圍
                    If sngTotalLength + 0.5 <= TheLength Then
                        intPosition += 1
                    Else
                        Exit For
                    End If
                Next

                Return Left(TheMixedString, intPosition + 1)
            End If

        Catch ex As Exception
            Throw New Exception("HalfWay, " & ex.Message)
        End Try
    End Function


arrow
arrow
    全站熱搜

    Roger 發表在 痞客邦 留言(0) 人氣()