2012-04-17 101 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

相關問題