2012-04-17 100 views
0

这应该相当简单,但我有一个这样的日子。任何人都可以告诉我如何替换字符串中的第一个和第三个字符?我已经看过替换,但不能工作,因为字符串可能有不同的长度。我想要做的就是取代第一次和第三次。替换字符串的第n次出现

+0

第一次和第三次发生的特定字符?字符,如在制表符字符例如?是这个答案还是这只是字符串的第一个和第三个字符 – aspiringCoder 2012-04-17 15:43:27

回答

4

IndexOf方法存在过载,该方法将起始位置作为参数。使用循环,您将能够找到第一个和第三个事件的位置。然后,您可以使用RemoveInsert方法的组合来进行替换。

您也可以使用StringBuilder进行替换。 StringBuilder有一个Replace方法,您可以为其指定开始索引和受影响的字符数。

0

aspiringCoder,

也许这样的事情可能对你有用的(与何元奈特在谈论< +1行>)

Dim str As String = "this is a test this is a test this is a test" 
Dim first As Integer 
Dim third As Integer 
Dim base As Integer = 0 
Dim i As Integer 
While str.length > 0 
    If i = 0 Then 
     first = str.IndexOf("test") 
    else if i = 2 Then 
     third = base + str.IndexOf("test") 
    end if 
base = base + str.IndexOf("test") 
str = str.Remove(0, str.IndexOf("test") + "test".length -1) 
i++ 
End While 

它可能有一个一次性的错误某处......但这至少应该让你开始。

+0

如果这是一个新的行字符,会发生什么? – aspiringCoder 2012-04-17 16:47:41

+0

得到它永不知道 – aspiringCoder 2012-04-17 16:56:07

+0

....似乎无法得到此代码工作? – aspiringCoder 2012-04-18 00:19:42

相关问题