半形字全形字

14:32 0 Comments A+ a-

將英數等半形符號,每兩個字元視為一個全形字/長度

昨天,頭兒突然說,如果發文時,將兩個半形字視為一個長度時,那麼可以讓發文串(有限字數)看起來比較飽滿。
然後便動手寫下了這個簡單的應用。
參考文章,關於 字元 的 半形 / 全形 轉換

    ''' <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


the code from http://www.dotblogs.com.tw