如何计算字符串中字符的第 n 次出现(位置)?
How to count the nth occurence (position) of a character in a string?
我正在尝试使用 vb.net winforms 制作刽子手游戏(用于学校项目),我想知道如何计算字符串中字符出现的第 n 个位置。
dim randomstring as string = "Whosebug"
For int As Integer = 0 To randomstring.Length - 1
Label2.Text &= "_ "
Next
如果我想在随机字符串中找到“o”的出现,我希望输出为“6, 12”,然后我会将 label2.text 中的下划线替换为其中的 o具体位置。有什么方法可以做到这一点,甚至有更好的方法吗?
.NET 数组以索引 0 开头。String
是 Char
的数组。这就是 IndexOf
的工作原理,以及我们如何逐个字符地遍历字符串。字符串被视为数组。
'To find the first index
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s = "The quick brown fox jumped over the lazy dogs."
Dim i = s.IndexOf("o")
MessageBox.Show(i.ToString)
End Sub
'To find index of all occurances
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim s = "The quick brown fox jumped over the lazy dogs."
Dim i As Integer
Dim lst As New List(Of Integer)
For Each c In s
If c = "o" Then
lst.Add(i)
End If
i += 1
Next
'See what is in the list
For Each item In lst
Debug.Print(item.ToString)
Next
'Prints in Immediate Window
'12
'17
'27
'42
End Sub
我正在尝试使用 vb.net winforms 制作刽子手游戏(用于学校项目),我想知道如何计算字符串中字符出现的第 n 个位置。
dim randomstring as string = "Whosebug"
For int As Integer = 0 To randomstring.Length - 1
Label2.Text &= "_ "
Next
如果我想在随机字符串中找到“o”的出现,我希望输出为“6, 12”,然后我会将 label2.text 中的下划线替换为其中的 o具体位置。有什么方法可以做到这一点,甚至有更好的方法吗?
.NET 数组以索引 0 开头。String
是 Char
的数组。这就是 IndexOf
的工作原理,以及我们如何逐个字符地遍历字符串。字符串被视为数组。
'To find the first index
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim s = "The quick brown fox jumped over the lazy dogs."
Dim i = s.IndexOf("o")
MessageBox.Show(i.ToString)
End Sub
'To find index of all occurances
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim s = "The quick brown fox jumped over the lazy dogs."
Dim i As Integer
Dim lst As New List(Of Integer)
For Each c In s
If c = "o" Then
lst.Add(i)
End If
i += 1
Next
'See what is in the list
For Each item In lst
Debug.Print(item.ToString)
Next
'Prints in Immediate Window
'12
'17
'27
'42
End Sub