如何替换逗号分隔字符串索引处的值?

时间:2015-12-08 17:37:51

标签: .net vb.net

如何根据标题行替换逗号分隔文件中特定列的值?我不想使用.Replace,因为它将替换它找到的所有数据,并且找到第一次出现的任何字符串函数都可以找到错误的事件。

逗号分隔文件的标题行: 文件名,所有者,物种,年龄,列n

我需要将文件的行索引2中的物种从Cat更改为Dog。我不能做一个简单的查找和替换,因为所有者的名称或文件名可能包含字符串Cat。例如,凯瑟琳。

示例文件:

File Name, Owner, Species, Age, Column n
C:\SomeFileName\, Catherine, Cat, 4, Caterpillar
C:\CatsAndDogs, CatterShark, Cat, 5, Foo

我知道Species位于第2列。

我正在尝试遍历文本文件并执行以下操作:

If MyTextFile(m).Split(",")(2) = "Cat" Then
    MyTextFile(m).Split(",")(2) = "Dog"
End If

该文件看起来像:

File Name, Owner, Species, Age, Column n
C:\SomeFileName\, Catherine, Cat, 4, Caterpillar
C:\CatsAndDogs\, CatterShark, Cat, 5, Foo

根据ChrisF的答案回答 - 将行转换为列表以获取索引并替换索引处的值,转换回逗号分隔的字符串。见下文。

Dim MyFileAsListOfRows As List(Of String) = IO.File.ReadAllLines(PathAndFileName).ToList()
Dim delimiter As String = ","

' Read the first line into a header row into a list
Dim headerRow As List(Of String) = MyFileAsListOfRows(0).Split(delimiter).ToList()
Dim idxSpecies As Int16 = headerRow.IndexOf("""Species""")


Dim originalText As String = "Cat"
Dim newText As String = "Dog"

For m As Integer = 0 To MyFileAsListOfRows.Count() - 1

    Dim currentRecord As List(Of String) = MyFileAsListOfRows(m).Split(delimiter).ToList()

    If CurrentRowInLoop(indexOfSpecies) = originalText Then
        CurrentRowInLoop(indexOfSpecies) = newText
    End If

    ' Use String.Join to convert the list of values in this row back to a comma delimited string and replace the old string with the new string.
    MyFileAsListOfRows(m) = String.Join(delimiter, CurrentRowInLoop)

Next

' Write all lines to file
IO.File.WriteAllLines(PathAndFileName, MyFileAsListOfRows)

2 个答案:

答案 0 :(得分:1)

您想要拆分文本,替换第一次出现的“Cat”,然后将文本重新加入输出字符串中:

var words = MyTextFile(m).Split(",")
if words(1) = "Cat" then
    words(1) = "Dog"
end if

var result = String.Join(",", words)

语法可能有点时髦,因为我不习惯将VB.NET写在脑海中

答案 1 :(得分:1)

您可以使用IndexOf查找Cat的第一个出现,然后使用Substring使用位置前后的两个部分重建字符串

Dim idx = MyTextFile(m).IndexOf("Cat")
if idx <> -1 Then
    MyTextFile(m) = MyTextFile(m).Substring(0, idx) & "Dog" & _
                    MyTextFile(m).Substring(idx+3)
End If