2017-05-22 125 views
0

我需要將代碼(123456)添加到文件中的一行文本中。查找字符串中字符的位置

\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\ 

代碼需要在第三個「\」之後輸入,所以它看起來像這樣。

\\ESSEX [D]\123456\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\ 

文本始終位於文件的第124行。

+0

確實[d]改變或總是一樣的? – Mederic

+0

Stackoverflow是你的朋友:https://stackoverflow.com/questions/26420143/how-to-get-the-nth-line-from-a-string和https://stackoverflow.com/questions/2571716/find-在字符串中出現第n個字符 – momo

+0

它並不總是不幸的。 – higsonboson

回答

1

如果[d]總是有一個短期和簡單的方法是做:

Dim MyString As String = "\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\" 
MyString = MyString.Insert(MyString.IndexOf("[D]") + 3, "123456") 

否則,你可以這樣做:

Dim MyString As String = "\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\" 
Dim d As Integer = 0 
For Each i As Match In Regex.Matches(MyString, "\\") 
    If d = 2 Then 
     MsgBox(MyString.Insert(i.Index + 1, "132456")) 
    End If 
    d = d + 1 
Next 
1

您可以使用File.ReadAllLinesFile.WriteAllLines和字符串方法:

Dim lines = File.ReadAllLines(path) 
If lines.Length < 124 Then Return 
Dim line = lines(123) 
Dim tokens = line.Split(New String() {"\"}, StringSplitOptions.None) 
If tokens.Length < 4 Then Return 
tokens(3) = "123456" 
lines(123) = String.Join("\", tokens) 
File.WriteAllLines(path, lines) 
0

我只是通過字符串循環,計算出現t他反斜槓,然後退出,當你發現第三次發生。

你需要保證指數的計數,然後利用此功能String.Insert方法插入「123456」的代碼:

Dim s As String = "\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\" 

Dim count As Integer = 0 
Dim index As Integer = 0 
For Each c In s 
    If c = "\" Then count += 1 
    index += 1 
    If count = 3 Then Exit For 
Next 

s = s.Insert(index, "123456") 

輸出:

\\ESSEX [D]\123456\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\ 
相關問題