vb.net - 检查子字符串在字符串中出现的次数
问题描述
我需要创建一个 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
我希望有一个人可以帮助我。提前致谢!
解决方案
可能会出现三种可能的结果:
- 没有出现
- 一次出现
- 多次出现
正如 jmcilhinney 所建议的,您可以使用IndexOf和LastIndexOf来帮助您做出决定。
如果未找到该字符串,则返回 -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
推荐阅读
- cross-compiling - 为不同的目标 Linux 架构编译 Kotlin Coroutines 依赖项
- javascript - 如何使用 angular 的 $timeout 的每个循环更新 $scope
- python - Python Flask mongoengine/pymongo:mongo 的 27018 端口上的连接被拒绝
- c++ - 奇怪的计算着色器延迟
- pgadmin - pgAdmin 是否有任何#region start ---- #region end
- amazon-web-services - 检查我的 AWS 应用程序负载均衡器是否将请求转发到正确的目标组?
- node.js - 几次成功请求后数据变为空 - 节点服务应用程序池缓存
- c++ - DLL LoadLibrary 函数在加载 msvcr100.dll 时返回错误代码 193
- .net - 如何避免对 ConcurrentBag 的争用
.GetEnumerator() - python - 使用 Python 请求 Zebra 打印机的状态