我想在字符串中选择一个随机空格并将其替换为单词(%word%),但是存在问题。该位置无法修复,因为我希望它随机插入。我考虑的几件事情:
1)在空格处打破字符串并将其与单词合并 2)找到一个随机空间并用单词替换它。我喜欢这一点,到目前为止我只是将selectedtext分解为字符串数组,然后迭代每一行。但我不知道如何找到一个随机的字符串位置?请问任何简短的甜蜜代码?
If (rtfArticle.SelectedText.Length > 0) Then
Dim strArray As String() = rtfArticle.SelectedText.Split(New Char() {ChrW(10)})
For Each str3 As String In strArray
If (str3.Contains(" ") = True) Then
End If
Next
End If
答案 0 :(得分:1)
您可以使用Random
类生成随机位置索引。
Dim testString = "This is just a test for random position"
Dim random = New Random()
Dim randomPos = random.Next(0, testString.Length - 1)
Debug.Print(String.Format("Char at Pos {0} = {1}", randomPos, testString.ElementAt(randomPos)))
答案 1 :(得分:0)
您可以在字符串中找到空格,随机选择一个并替换它。类似的东西:
' Get string
Dim data As String = rtfArticle.SelectedText
' Get space positions
Dim spaces As New List(Of Integer)
For i As Integer = 0 to data.Length - 1
If data(i) = " "C Then spaces.Add(i)
Next
' Get a random space
Dim rnd As New Random()
Dim pos As Integer = spaces(rnd.Next(spaces.Length))
' Remove the space
data = data.Remove(pos, 1)
' Insert the replacement
data = data.Insert(pos, "%word%")
' Put the string back
rtfArticle.SelectedText = data