Register  |  
About the author
Baldwin's Status
 Contact Me
Baldwin Sun
Senior Developer for dnn solution & founder of SunBlog module...
Blog搜索
相册库
更多照片请查看相册库
最新评论
Rss Feed
feedsky
抓虾
pageflakes
newsgator
哪吒
我们的服务
  • DotNetNuke 咨询
  • Web设计及其模块开发
  • 免费建站
  • 电子商务
  • 开拓市场
我们致力于开发定制的web 2.0 ,所服务的客户主要包括小中型企业,社区俱乐部及其非盈利机构组织。我们将利用开源的DNN作为我们核心的系统机制,更多相关信息...

TrimEnd() Vs SubString

Posted in [DNN模块开发], [杂项] By baldwin

一般我们在处理分隔符时首先都会想到循环或遍历, 最后使用SubString函数截掉最后一个默认添加的分隔符, 代码类似:

out = out.Substring( 0, out.LastIndexOf( ',' )

然而其实还有更简洁的方式处理类似情况, 那就是TrimEnd函数的应用:

out = out.TrimEnd(',')

TrimEnd接收的参数是char类型的数组, 故你可以添加不同的分隔符(单个或多个), 如此可以组合出来任意你需要的分隔字符串. 在此举一个例子, 那就是本Blog(代码"SunBlog“)的Tag功能, 存储的是带有分隔符”|“的Tags字符串, 而在页面呈现时需要对此进行格式化, 最终得到的应该是带有链接的Tags列表, 利用余下代码可实现之:(注意比较不同方法的实现方式: SubString, Join, TrimEnd)

'writes out a comma separated value list with the loop and String.SubString
Private Function BuildTagsList(ByVal tagToken As TagsToken, ByVal separateRule As String) As String
Dim tagsArray As String() = tagToken.TagsList.Split(separateRule)
 
Dim tag As String
Dim tagsTemplate As String = String.Empty
For Each tag In tagsArray
    tagsTemplate += String.Format(LocalizationByKey("TagsList", True), Utility.TagsViewLink(), tag)
    tagsTemplate += ", "
Next
 
Return tagsTemplate.Substring(0, tagsTemplate.LastIndexOf(", "))
End Function
 
' writes out a comma separated value list with the String.Join
Private Function BuildTagsList(ByVal tagToken As TagsToken, ByVal separateRule As String) As String
Dim tagsArray As String() = tagToken.TagsList.Split(separateRule)
 
Dim tags As String() = New String(tagsArray.Length - 1) {}
Dim i As Integer = 0
For Each tag As String In tagsArray
    tags(i) = String.Format(LocalizationByKey("TagsList", True), Utility.TagsViewLink(), tag)
    i += 1
Next
 
Return String.Join(", ", tags)
End Function
 
'writes out a comma separated value list with the TrimEnd
Private Function BuildTagsList(ByVal tagToken As TagsToken, ByVal separateRule As String) As String
Dim tagsArray As String() = tagToken.TagsList.Split(separateRule)
 
Dim tagsTemplate As String = String.Empty
For Each tag As String In tagsArray
    tagsTemplate += String.Format(LocalizationByKey("TagsList", True), Utility.TagsViewLink(), tag)
    tagsTemplate += ", "
Next
 
'注意这是Char数组, 如果是单个分隔符你可以直接使用tagsTemplate.TrimEnd(","c)
Dim trim_str As Char() = {","c, " "c}
Return tagsTemplate.TrimEnd(trim_str)
End Function

对应还有TrimStart函数, 不过是针对字符串的首端处理.

Comments

Was it good for you, too?Join the discussion » ,but you need to login first before you make comments.