Public Function
strCutOut(ByVal p_str As String, ByVal p_len As Integer) As
String
Dim strNew As String = String.Empty
Try
Dim
intLenbyByte As Integer =
System.Text.Encoding.UTF8.GetByteCount(p_str)
'按照UTF8编码方式取得p_str的字节数
If
intLenbyByte <= p_len Then
strNew = p_str
Return
strNew
End
If
Dim
intWholeLenByCha As Integer = p_str.Length '按字符个数计算总长度
Dim
intWholeLenByByte As Integer = 0
'按字符字节数计算总长度
Dim
intHalfLenByCha As Integer = 0
'因为用的是二分法,所以存储每次所需取得的字符个数的一半
Dim
intLastIndexByCha As Integer = 0
'上一次计算时的字符的个数
For i = 0
To p_str.Length - 1
If i = 0 Then
strNew = p_str.Substring(0, intWholeLenByCha /
2)
intHalfLenByCha = intWholeLenByCha / 2
Else
strNew = p_str.Substring(0, i)
End If
intWholeLenByByte =
System.Text.Encoding.UTF8.GetByteCount(strNew)
If intWholeLenByByte = p_len
Then
Return strNew
ElseIf intWholeLenByByte
< p_len Then
intLastIndexByCha = i
intHalfLenByCha = (intWholeLenByCha - (i + 1)) /
2 '总字符长度需要减的字符个数应该是index i +1
i = i + intHalfLenByCha
Else
If intLastIndexByCha = i - 1 Then
'满足if条件时表明特殊字符占多个字节,且刚好卡在临界位
strNew =
p_str.Substring(0, intLastIndexByCha)
Return
strNew
End If
i = intLastIndexByCha + intHalfLenByCha /
2
intHalfLenByCha = intHalfLenByCha / 2
End If
Next
Return
strNew
Catch ex As Exception
Return
ex.ToString
End Try
End Function