gpt4 book ai didi

vb.net - 多个 if 语句检查字符串长度并缩短

转载 作者:行者123 更新时间:2023-12-01 22:50:41 26 4
gpt4 key购买 nike

我想知道是否有更好的方法来编写这些多个 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

非常感谢任何帮助。

最佳答案

您可以使用 LINQ:

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

要求解释(我发现这实际上很容易理解):

由于字符串实现了 IEnumerable(Of Char),因此您可以像字符集合一样使用它。 LINQ 扩展方法 Enumerable.All 确定序列/集合中的所有项目是否与给定的 predicate 匹配。 (返回True)。在这种情况下,谓词检查给定的 char 是否为 "-"c(末尾的 c 对于 option strict on 是必需的,以告诉编译器这是一个 char而不是字符串)。因此,只有当字符串中的所有字符都是负数时,此方法才会返回 True。一旦 All 找到不同的字符,它将返回 False

如果它返回True,则有 1-n 个减号且没有其他字符,因此变量 text 可以是 "-"

关于vb.net - 多个 if 语句检查字符串长度并缩短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45368014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com