2017-07-28 89 views
2

我想知道是否有更好的方式来编写这些多个If语句?我确定有,我不知道它会是什么。本质上,代码只是缩短了字符串。多if语句检查字符串的长度和缩短

   If text = "-----------------" Then 
        text = "-" 
       End If 
       If text = "----------------" Then 
        text = "-" 
       End If 
       If text = "---------------" Then 
        text = "-" 
       End If 
       If text = "--------------" Then 
        text = "-" 
       End If 
       If text = "-------------" Then 
        text = "-" 
       End If 
       If text = "------------" Then 
        text = "-" 
       End If 
       If text = "-----------" Then 
        text = "-" 
       End If 
       If text = "----------" Then 
        text = "-" 
       End If 
       If text = "---------" Then 
        text = "-" 
       End If 
       If text = "--------" Then 
        text = "-" 
       End If 
       If text = "-------" Then 
        text = "-" 
       End If 
       If text = "------" Then 
        text = "-" 
       End If 
       If text = "-----" Then 
        text = "-" 
       End If 
       If text = "----" Then 
        text = "-" 
       End If 
       If text = "---" Then 
        text = "-" 
       End If 
       If text = "--" Then 
        text = "-" 
       End If 

任何帮助,非常感谢。既然字符串实现IEnumerable(Of Char)你可以使用它像字符的集合

+0

你可以使用正则表达式;我记得,识别单个字符的任意数量的重复是非常简单的。如果性能是一个问题,我建议分析;就像你发布的代码一样丑陋,它可能比任何其他代码都快。 – Craig

回答

5

你可以使用LINQ:

If text.Length > 0 AndAlso text.All(Function(c) c = "-"c) Then text = "-" 

要求的解释(我发现这实际上是非常可以理解的)。 LINQ扩展方法Enumerable.All确定序列/集合中的所有项目是否匹配给定的predicate(返回True)。在这种情况下,谓词检查给定的字符是否为"-"c(最后的c是option strict on以告诉编译器这是一个字符而不是字符串)。所以只有当字符串中的所有字符都是不合适的时候,这个方法才会返回True。只要All发现不同的字符,它将返回False

如果它返回True有1-n个使用者并且没有其他字符,所以变量text可以是"-"

+0

Downvoted,因为尽管代码片段没问题,但没有一些尝试解释代码片段正在做什么的问题,答案并不值得。 –

+0

@AlessandroMandelli:固定 –

+0

好,upvoted。现在它在帮助。 –

0

怎么样?:

Dim maxLengthOfStringYouCompareTo As Integer = 17 

Dim xxx As String = "" 

Dim text As String = If((xxx.All(Function(charrr) charrr.ToString() = "-") OrElse xxx.Length <= maxLengthOfStringYouCompareTo), "-", "otherValue") 

,但如果不需要限制,然后取出

xxx.Length <= maxLengthOfStringYouCompareTo 
0
While text.Contains("--") 
    text = text.Replace("--","-") 
End While 
+1

这是一个很酷的方式! –

+0

我之前就曾对此评论做过低评价:我相信你会被拒绝投票,因为虽然代码片段没问题,但如果没有尝试解释代码片段正在做什么,那么答案并不值得。 - Mike_OBrien 6月13日16:11 Mike的评论最多发表了4次。 基于同样的原理,上面的两个答案也应该被低估。 –

+0

这是很明显的代码段正在做什么,虽然...不是吗?似乎有点迂腐。 –