查找字符串中字符的位置

时间:2017-05-22 14:30:19

标签: vb.net text-files

我需要将代码(123456)添加到文件的一行文本中。

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

代码需要在第3个“\”之后输入,所以它看起来像这样。

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

文本始终位于文件的第124行。

3 个答案:

答案 0 :(得分: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 :(得分: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)

答案 2 :(得分:0)

我只是循环遍历字符串,计算反斜杠的出现次数,然后在找到第三次出现时退出。

您需要保留索引的计数,然后将其与String.Insert方法一起使用以插入&#34; 123456&#34;代码:

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\\\\\\\\\\\\\\\\\\\\\\\