用逗号分隔替换文本文件中的字符

时间:2016-12-13 08:14:36

标签: vb.net

我有一个包含示例值的逗号分隔文件: 1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT

问题:如何替换最后一栏中的逗号,即#34; AAA,TEXT"

结果应该是这样的: 1,1076103,22-NOV-16,21051169,50,1083,AAATEXT

2 个答案:

答案 0 :(得分:2)

an overload of String.Split有一个参数告诉它要返回的最大部件数。您可以像这样使用它:

Option Infer On
Option Strict On

Module Module1

    'TODO: think up a good name for this function
    Function X(s As String) As String
        Dim nReturnParts = 7
        Dim parts = s.Split({","c}, nReturnParts)
        If parts.Count < nReturnParts Then
            Throw New ArgumentException($"Not enough parts - needs {nReturnParts}.")
        End If

        parts(nReturnParts - 1) = parts(nReturnParts - 1).Replace(",", "")
        Return String.Join(",", parts)

    End Function

    Sub Main()
        Dim s() = {"1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT",
            "1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT",
            "1,1076103,22-NOV-16,21051169,50,1083,C,C,C,TEXT"}

        For Each a In s
            Console.WriteLine(X(a))
        Next

        Console.ReadLine()

    End Sub

End Module

输出:

  

1,1076103,22-NOV-16,21051169,50,1083,AAATEXT
  1,1076103,22-NOV-16,21051169,50,1083,BBBTEXT
  1,1076103,22-NOV-16,21051169,50,1083,CCCTEXT

答案 1 :(得分:0)

很简单,但学习一下如何使用字符串;)

Public Function MDP(strWork As String)
    Dim splitted() As String = strWork.Split(","c)
    Dim firsts As New List(Of String)

    For i As Integer = 0 To splitted.Count - 3
        firsts.Add(splitted(i))
    Next

    Dim result As String = System.String.Join(",", firsts)

    Return result & "," & splitted(splitted.Count - 2) & splitted(splitted.Count - 1)
End Function

然后致电:

 Dim finished As String = MDP("1,1076103,22-NOV-16,21051169,50,1083,AAA,TEXT")