Andrew Edwards
Andrew Edwards

Reputation: 11

VB 2010 - Replace all letters of a string with a dash

VB 2010 - Beginner here, I am creating a hangman game for a assignment and I am having trouble replacing the text of a string with dashes. I am not sure if I need to convert the string to a charArray() or if I can use the string.Replace function. i know i need to loop it unsure how..

terribly confused i need some help. As I am learning please try and keep it simple with reason please.

My sandbox code so far:

Imports System.IO

Public Class Form1

    Private Const TEST = "test.txt"

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim WordString As String = Nothing
        Dim NewWordInteger As Integer
        Dim RandomWord As New Random(System.DateTime.Now.Millisecond) 'Load a new word at the time it was initiated

        'Load words from test file into the array 
        Dim WordArray() As String = File.ReadAllLines(TEST) 'Reads words from list and declares each as a string
        'Select Random word from the number of words in the dictionary.txt file
        NewWordInteger = RandomWord.Next(0, 4)

        'Display RandomWord in textbox as STRING.. 
        WordString = WordArray(NewWordInteger) ' Assigns wordstring a word from the arrany & random by the NewWordInterger Substring.. 
        WordDisplayTextBox.Text = WordString ' will display the word in the textbox
        SolveLabel.Text = WordString ' will display the word in the Solve label

        'Will shoe the array word and the word/string position in the TEST.file
        ListBox1.Items.Add(WordString) ' will show the word
        ListBox2.Items.Add(NewWordInteger) ' will show the string position in the TEST.file

        'search string and replace letters with _ (Dashes)
        Dim charArray() As Char = WordDisplayTextBox.Text.ToCharArray

        For Each item As Char In WordDisplayTextBox.Text
            WordDisplayTextBox.Text = WordString.Replace(item, "_")
        Next

    End Sub

End Class

Upvotes: 1

Views: 2187

Answers (2)

FlashspeedIfe
FlashspeedIfe

Reputation: 378

Loop through the length of the WordString and each time write "__" inside the WordDisplayTextBox

For i As Integer = 1 To Len(txtWordString.Text)

        WordDisplayTextBox.Text += "__" + " "    'Space separates the dashes for clarity
Next

Upvotes: 2

The other other Alan
The other other Alan

Reputation: 1918

If you want to replace all the characters of a string with dashes, why not just make a new string that consists only of dashes, that is the same length as the starting string? Isn't that the same thing?

WordDisplayTextBox.Text = New String("_", WordString.Length)

Upvotes: 4

Related Questions