想要在VB 6.0中的特定位置替换一个字符

时间:2015-04-09 10:36:40

标签: replace vb6

wordString - >填写空白的单词。 key - >替换字符。 我还有keyPos中密钥的位置,它是随机计算的

我正在填补空白游戏。在这里,我需要在随机位置创建空白。我正在使用Replace(wordString, key, "_", , 1)

但这只会取代第一次出现。如果我的wordString有重复的字母,如 APPLE ,它将始终替换第一个 P

我也要替换第二个 P 。像AP_LE一样。

2 个答案:

答案 0 :(得分:1)

我自己有另一个解决方案。 它有3个文本框txtInput,txtOutput,txtKeyPos和一个命令按钮command1

代码:

Private Sub Command1_Click()
t1 = Left$(txtInput.Text, Int(txtKeyPos.Text) - 1)
t2 = Right$(txtInput.Text, (Len(txtInput.Text)) - Int(txtKeyPos.Text))
txtOutput.Text = t1 & "_" & t2
End Sub

这符合我的目的。

答案 1 :(得分:0)

好的,这是vb.net而不是vb6,但这里是::

你应该采用单词方法而不是字符方法:

Dim sentence as String = "My apple is red."
Dim wordsInSentence() as String = sentence.Split()

Dim Rnd as new Random
Dim wordToBlank as String = wordsInSentence(Rnd.next(0, wordsInSentence.length))
Dim blankedSentence as String = sentence.Replace(wordToBlank, "___")

并且blankedSentence将包含您的sentence,其中包含一个随机单词。

My ___ is red.

编辑:要在字符串中删除随机字符,请将字符串中的字符索引随机化,如果不是空格,则将其空白:

Dim sentence as String = "My apple is red."

Dim Rnd as new Random
Dim index As single = Rnd.next(0, sentence.length)
While sentence.Substring(index,1) = " "
    index = Rnd.next(0, sentence.length)
End While

Dim blankedSentence as String = sentence.Remove(index,1).Insert(index, "_")

blankedSentence包含您的sentence,其中包含随机的非空格字母:

My ap_le is red.

这不是一个非常好的方法,因为所有单词的所有字母,包括标点符号,都可以是被消隐的字符。除此之外,它将为您提供您想要的东西。

VB6版本:

Dim sentence as String
Dim index As Integer
Dim intUpperBound As Integer
Dim intLowerBound As Integer

sentence = "My apple is red."
intLowerBound = 1 'assuming the first character of the word
intUpperBound = Len(sentence)

Randomize 'initialize the random number generator
index = Int((intUpperBound - intLowerBound + 1) * Rnd) + intLowerBound
While Mid$(sentence, index, 1) = " "
    index = Int((intUpperBound - intLowerBound + 1) * Rnd) + intLowerBound
Wend

Dim blankedSentence As String
blankedSentence = sentence
Mid(blankedSentence, index, 1) = "_" 'replace the current character at index with the new character