缩短代码,如果相等则替换文本

时间:2019-06-26 17:11:23

标签: vb.net

我想缩短这段代码,可以吗?我将在计时器中使用此代码。 即,如果显示的文本包含一个Q1到Q的无限Q,则该文本将被替换为“”,并且PictureBox将显示与问题相对应的图像(该Q,即该图像也将称为Q1到Q无限。)我将在计时器中使用此代码。

If QuestionBox.Text.Contains("Q1") Then
    QuestionBox.Text = QuestionBox.Text.Replace("Q1", "")
    PictureBox.Image = Image.FromFile(My.Application.Info.DirectoryPath + ("\Gfx\Q1.jpg"))
ElseIf QuestionBox.Text.Contains("Q2") Then
    QuestionBox.Text = QuestionBox.Text.Replace("Q2", "")
    PictureBox.Image = Image.FromFile(My.Application.Info.DirectoryPath + ("\Gfx\Q2.jpg"))
ElseIf QuestionBox.Text.Contains("Q3") Then
    QuestionBox.Text = QuestionBox.Text.Replace("Q3", "")
    PictureBox.Image = Image.FromFile(My.Application.Info.DirectoryPath + ("\Gfx\Q3.jpg"))
ElseIf QuestionBox.Text.Contains("Q4") Then
    QuestionBox.Text = QuestionBox.Text.Replace("Q4", "")
    PictureBox.Image = Image.FromFile(My.Application.Info.DirectoryPath + ("\Gfx\Q4.jpg"))
ElseIf QuestionBox.Text.Contains("Q5") Then
    QuestionBox.Text = QuestionBox.Text.Replace("Q5", "")
    PictureBox.Image = Image.FromFile(My.Application.Info.DirectoryPath + ("\Gfx\Q5.jpg"))
ElseIf QuestionBox.Text.Contains("Q6") Then
    QuestionBox.Text = QuestionBox.Text.Replace("Q6", "")
    PictureBox.Image = Image.FromFile(My.Application.Info.DirectoryPath + ("\Gfx\Q6.jpg"))
ElseIf QuestionBox.Text.Contains("Q7") Then
    QuestionBox.Text = QuestionBox.Text.Replace("Q7", "")
    PictureBox.Image = Image.FromFile(My.Application.Info.DirectoryPath + ("\Gfx\Q7.jpg"))
ElseIf QuestionBox.Text.Contains("Q8") Then
    QuestionBox.Text = QuestionBox.Text.Replace("Q8", "")
    PictureBox.Image = Image.FromFile(My.Application.Info.DirectoryPath + ("\Gfx\Q8.jpg"))
End If

我尝试的是,不幸的是没有用。

Dim testString = "aaaaaQ1"
If testString.Contains("Q") Then
    Dim numero As String = Split(testString, "Q")(1)
    QuestionBox.Text = testString.Replace("Q" & numero, "")
    PictureBox.Image = Image.FromFile(My.Application.Info.DirectoryPath + ("\Gfx\Q" & numero & ".jpg"))
End If

1 个答案:

答案 0 :(得分:0)

我不太确定Q Infinite是什么意思,但是您可以使用循环替换上面的代码(我的VB可能有点生锈):

Const MaxQ As Long = 8 ' Can be changed to meet you needs
Dim i As Integer

For i = 1 To MaxQ
    Dim s As String = $"Q{i}"
    If (QuestionBox.Text.Contains(s)) Then
        QuestionBox.Text = QuestionBox.Text.Replace(s, "")
        Image = Image.FromFile(My.Application.Info.DirectoryPath + ($"\Gfx\{s}.jpg"))
        Exit For
    End If
Next