VB 2010 - 用短划线替换字符串的所有字母

时间:2013-05-03 14:52:37

标签: vb.net visual-studio-2010

VB 2010 - 初学者, 我正在为作业创建一个刽子手游戏,我无法用破折号替换字符串的文本。我不确定是否需要将字符串转换为charArray()或者我是否可以使用string.Replace函数。我知道我需要循环它不确定如何..

非常困惑我需要一些帮助。正如我正在学习的那样,请尽量保持简单。

到目前为止我的沙箱代码:

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

2 个答案:

答案 0 :(得分:4)

如果你想用破折号替换字符串的所有字符,为什么不只是创建一个只包含破折号的新字符串,它与起始字符串的长度相同?这不是一回事吗?

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

答案 1 :(得分:2)

循环遍历WordString的长度,每次写入" __"在WordDisplayTextBox中

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

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