Sp4Rx
Sp4Rx

Reputation: 1668

Want to replace one character at specific position in VB 6.0

wordString --> Word for fill in the blank. key-->Character is replaced. I have also have the position of the key in keyPos which is calculated randomly

I'm making a fill in the blanks game. Here I need to create blanks at random position. I'm using Replace(wordString, key, "_", , 1)

But this only replace the first occurrence. If my wordString has repeating letters like APPLE it will always replace the first P

I want to replace the second P also. Like AP_LE.

Upvotes: 1

Views: 6137

Answers (2)

Sp4Rx
Sp4Rx

Reputation: 1668

I got another solution myself. It has 3 text boxes txtInput, txtOutput, txtKeyPos and a command button command1

Code:

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

This serves my purpose.

Upvotes: 1

Viktor Ek
Viktor Ek

Reputation: 353

OK this is vb.net and not vb6 but here goes::

You should do a word approach instead of a character approach:

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, "___")

And blankedSentence will contain your sentence with a random word blanked.

My ___ is red.

EDIT: To instead blank a random character in your string, randomise a character index in your string and (if it's not a space) blank that :

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, "_")

And blankedSentence contains your sentence with a random non-space letter blanked:

My ap_le is red.

This isn't a very good approach though as all letters of all words, including punctuation, can be the character that is blanked. Other than that it will get you what you wanted.

VB6 version:

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

Upvotes: 0

Related Questions