用重写FORMAT方法来实现 .NET 的自动文本缩减

Public Class myFormat : Inherits Page
        Implements IFormatProvider
        Implements ICustomFormatter
        '重写FORMAT接口
#Region "重写FORMAT接口"
        Public Function GetFormat(ByVal formatType As System.Type) As Object Implements System.IFormatProvider.GetFormat
            If formatType.ToString = GetType(ICustomFormatter).ToString Then
                Return Me
            Else
                Return Nothing
            End If
        End Function
        Public Function Format(ByVal theformat As String, ByVal arg As Object, ByVal formatProvider As System.IFormatProvider) As String Implements System.ICustomFormatter.Format
            If theformat Is Nothing Then
                Return String.Format("{0}", arg)
            End If
            If Not theformat.StartsWith("L") Then
                If TypeOf arg Is IFormattable Then
                    Return CType(arg, IFormattable).ToString(Format, formatProvider)
                End If
                If (arg Is Nothing) Then
                    Return arg.ToString()
                End If
            End If
            '使用格式字符串对输出字符串进行格式化
            theformat = theformat.Trim(New Char() {"L"c})
            Dim b As Integer = Convert.ToInt32(theformat)
            Dim Str As String = arg.ToString
            Dim StrByte As Byte() = System.Text.Encoding.GetEncoding("gb2312").GetBytes(Str)
            Dim StrByte2(b * 2 - 1) As Byte
            If StrByte.Length > b * 2 Then
                Dim i As Integer
                If StrByte(b * 2) < 128 Then
                    Array.Copy(StrByte, StrByte2, b * 2 - 1)
                    StrByte2(b * 2 - 1) = StrByte(b * 2 - 1)
                    Return System.Text.Encoding.GetEncoding("gb2312").GetString(StrByte2) & "..."
                Else
                    Array.Copy(StrByte, StrByte2, b * 2)
                    Return System.Text.Encoding.GetEncoding("gb2312").GetString(StrByte2) & "..."
                End If
            Else
                Return Str
            End If
        End Function
#End Region
    End Class

使用string.format(new myFormat,"{0:L长度数值}",需格式化字符串) 就能输出一定长度的字符串
例:
dim str as string = "12345678901234567890"
response.write(string.format(new myFormat,"{0:L15}",str)
输出结果为  "123456789012345"
判断了中英文结合情况,输出结果是 [中文字+英文字] 个
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值