您的位置:首页 > 编程语言

写了一个字符串截取一定长度的代码,中文两个字符,英文一个字符,如果截断了自动用一个.或两个.来对齐,用于标题的显示

2009-03-26 08:59 946 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: