Public Class myFormat : Inherits Page
Implements IFormatProvider
Implements ICustomFormatter
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
#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 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
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
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)
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)
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
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"
dim str as string = "12345678901234567890"
response.write(string.format(new myFormat,"{0:L15}",str)
输出结果为 "123456789012345"
判断了中英文结合情况,输出结果是 [中文字+英文字] 个