16,554
社区成员
发帖
与我相关
我的任务
分享
Imports System.Runtime.CompilerServices
Public Module StringExtensions
<Extension()> _
Public Function HalfSubstring(ByVal str As String, ByVal strLength As Integer) As String
strLength = strLength - 1
Dim newStr As String = String.Empty
Dim p As Integer
For i As Integer = 0 To str.Length - 1
Dim subStr As String = str.Substring(i, 1)
If (Regex.IsMatch(subStr, "[\u4e00-\u9fa5]")) Then
p += 2
newStr &= subStr
Else
p += 1
newStr &= subStr
End If
If p > strLength Then
If p > strLength + 1 And (Regex.IsMatch(subStr, "[\u4e00-\u9fa5]")) Then
newStr = newStr.Substring(0, newStr.Length - 1) & "."
Exit For
Else
If (Regex.IsMatch(newStr.Substring(newStr.Length - 1, 1), "[\u4e00-\u9fa5]")) Then
newStr = newStr.Substring(0, newStr.Length - 1) & ".."
Else
newStr = newStr.Substring(0, newStr.Length - 1) & "."
End If
Exit For
End If
End If
Next
Return newStr
End Function
End Module
Public Function HalfSubstring(ByVal str As String, ByVal strLength As Integer) As String
If System.Text.Encoding.Unicode.GetByteCount(str) < strLength Then
Return str
End If
Dim bytesStr() As Byte = System.Text.Encoding.Unicode.GetBytes(str)
Dim list As List(Of Byte) = New List(Of Byte)()
Dim count As Integer = 0
For i As Integer = 0 To bytesStr.Length - 1 Step 2
If count = strLength Then
Exit For
End If
If bytesStr(i + 1) = 0 Then
If count + 1 = strLength Then
list.Add(46)
list.Add(0)
count += 1
Else
list.Add(bytesStr(i))
list.Add(bytesStr(i + 1))
count += 1
End If
Else
If count + 2 > strLength Then
list.Add(46)
list.Add(0)
count += 1
ElseIf count + 2 = strLength Then
list.Add(46)
list.Add(0)
list.Add(46)
list.Add(0)
count += 2
Else
list.Add(bytesStr(i))
list.Add(bytesStr(i + 1))
count += 2
End If
End If
Next
Return System.Text.Encoding.Unicode.GetString(list.ToArray())
End Function