如何用另一个字符串

时间:2016-08-09 17:21:18

标签: vb.net

你能帮我解决一下如何获取相同字符串的索引并将其逐个替换为另一个字符串吗?

这是我的示例代码:

For i As Integer = 0 To 10
    Dim str As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
    Dim replace As String = "efgh"
    Dim value As String
    value = str.Replace("abcd", replace)
    TextBox4.AppendText(value)
Next

价值将是结果: efgh,efgh,efgh,efgh,efgh ......

我如何创建这样的结果:

EFGH ,ABCD,ABCD,ABCD,ABCD,ABCD ...

对于下一个循环,它将是这样的:

ABCD,的 EFGH 下,ABCD,ABCD,ABCD,ABCD ...

对于下一个循环,它将是这样的:

ABCD,ABCD,的 EFGH 下,ABCD,ABCD,ABCD ...

谢谢

2 个答案:

答案 0 :(得分:2)

有很多方法可以做到这一点。一种可能效率低下的方式是将字符串拆分为逗号,替换结果数组中的相应项,然后重新加入数组。

efgh,abcd,abcd,abcd,abcd,abcd,abcd,abcd
abcd,efgh,abcd,abcd,abcd,abcd,abcd,abcd
abcd,abcd,efgh,abcd,abcd,abcd,abcd,abcd
abcd,abcd,abcd,efgh,abcd,abcd,abcd,abcd
abcd,abcd,abcd,abcd,efgh,abcd,abcd,abcd
abcd,abcd,abcd,abcd,abcd,efgh,abcd,abcd
abcd,abcd,abcd,abcd,abcd,abcd,efgh,abcd
abcd,abcd,abcd,abcd,abcd,abcd,abcd,efgh

输出:

 <form id="FOO" method="POST" action="/pdf">

     <input type="text" name="object" >
     <button type="submit">Generate</button>

 </form>

答案 1 :(得分:0)

正如@Mark所说,有很多方法可以做到。在字符串中添加和删除范围的方法之一是使用StringBuilder

Imports System.Text

Public Class Form1
  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    For i As Integer = 0 To 35 Step 5
      Dim sDefaultString As String = "abcd,abcd,abcd,abcd,abcd,abcd,abcd,abcd"
      Dim sbText = New StringBuilder(sDefaultString)
      sbText.Remove(i, 4)
      sbText.Insert(i, "efgh")
      TextBox1.AppendText(sbText.ToString & vbNewLine)
    Next

  End Sub
End Class

enter image description here