Vb.net 检查子字符串在字符串中出现的次数
我需要创建一个MessageBox,该MessageBox根据单词在字符串中出现的次数进行调整。所以我应该能够计算一个单词在字符串中出现的次数。如果这超过1次,将显示特定消息。如果该词仅出现1次,则会出现另一条消息。为了清楚起见,我不需要知道子字符串在字符串中出现了多少次。只有当它发生不止一次时 例如,我有字符串Vb.net 检查子字符串在字符串中出现的次数,vb.net,Vb.net,我需要创建一个MessageBox,该MessageBox根据单词在字符串中出现的次数进行调整。所以我应该能够计算一个单词在字符串中出现的次数。如果这超过1次,将显示特定消息。如果该词仅出现1次,则会出现另一条消息。为了清楚起见,我不需要知道子字符串在字符串中出现了多少次。只有当它发生不止一次时 例如,我有字符串hello hi hello。我要检查一下“你好”这个词。这个词出现了好几次,因此会显示一个消息框,上面说这个词出现了多次。我不知道该怎么做,但我认为这将是我在下面写的代码附近的东西 D
hello hi hello
。我要检查一下“你好”这个词。这个词出现了好几次,因此会显示一个消息框,上面说这个词出现了多次。我不知道该怎么做,但我认为这将是我在下面写的代码附近的东西
Dim stringToCheck, stringToFind As String
stringToCheck = "hello hi hello"
stringToFind = "hello"
If ... Then
'The stringToFind appeared more than once in stringToCheck
MessageBox.Show($"The string {stringToFind} was found more then once.", "Found multiple times")
Else
'The stringToFind appeared only one time in stringToCheck
MessageBox.Show($"The string {stringToFind} was found one time.", "Found once")
End If
我希望有人能帮助我。提前谢谢 有三种可能的结果:
If…Else
块,它显示了正在检查的所有三种状态:
Dim stringToCheck, stringToFind As String
stringToCheck = "hello hi hello"
stringToFind = "hello"
Dim index1, index2 As Integer
index1 = stringToCheck.IndexOf(stringToFind)
If index1 <> -1 Then
index2 = stringToCheck.LastIndexOf(stringToFind)
End If
If index1 = -1 Then
MessageBox.Show($"The string {stringToFind} was NOT found.", "No occurrences")
ElseIf index1 = index2 Then
MessageBox.Show($"The string {stringToFind} was found ONCE.", "One occurrence")
Else
MessageBox.Show($"The string {stringToFind} was found MULTIPLE TIMES.", "Multiple occurrences")
End If
Dim stringToCheck,stringToFind As String
stringToCheck=“你好,你好”
stringToFind=“你好”
Dim index1,index2为整数
index1=stringToCheck.IndexOf(stringToFind)
如果index1-1,则
index2=stringToCheck.LastIndexOf(stringToFind)
如果结束
如果index1=-1,则
Show($“未找到字符串{stringToFind}。”,“未出现”)
ElseIf index1=index2然后
Show($“字符串{stringToFind}被找到一次。”,“一次出现”)
其他的
Show($“字符串{stringToFind}被多次找到。”,“多次出现”)
如果结束
如果IndexOf
和LastIndexOf
返回相同的值,则只有一个实例。。例如,Dim count=Regex.Matches(stringToCheck,stringToFind).count
如果您决定使用Regex,您需要小心使用stringToFind
,以防它包含正则表达式使用的特殊字符。为了安全起见,请确保使用Regex.Escape(stringToFind)
@jmchilhinney,除非它们都返回-1,在这种情况下没有实例。@Idle\u注意,正确。我使用了来自jmcillhinney的方法,对我来说效果很好。在我将其用于的情况下,在stringToCheck
中始终至少有一个stringToFind
。但是谢谢你的评论,因为我不知道!我的问题解决了。只有当IndexOf()
返回>=0
时,才可以检查LastIndexOf()
。