首页 > 解决方案 > 检查子字符串在字符串中出现的次数

问题描述

我需要创建一个 MessageBox 以适应单词在字符串中出现的次数。所以我应该能够计算一个单词在字符串中出现的次数。如果超过 1 次,就会出现特定的消息。如果这个词只出现 1 次,就会出现另一条消息。为了清楚起见,我不需要知道子字符串在字符串中出现了多少次。仅当它发生不止一次时。

例如,我有字符串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

我希望有一个人可以帮助我。提前致谢!

标签: vb.net

解决方案


可能会出现三种可能的结果:

  1. 没有出现
  2. 一次出现
  3. 多次出现

正如 jmcilhinney 所建议的,您可以使用IndexOfLastIndexOf来帮助您做出决定。

如果未找到该字符串,则返回 -1。如果字符串存在(-1 不返回),但只出现一次,那么这两个值将是相同的。如果这两个值不是 -1 并且不同,则存在多次出现。

这是一个简单的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

推荐阅读