【问题标题】:Find and Replace a particular Tab separated location in .NET string variable在 .NET 字符串变量中查找和替换特定的制表符分隔位置
【发布时间】:2014-03-20 12:27:44
【问题描述】:

我有一个带有 TAB 分隔数据的字符串。我想替换字符串中任意 TAB 位置的文本。

例如我想在 TAB 字符的第 5 次拆分处将“N/A”替换为“-1.0”。我可以用 string_data.split(vbtab)(4).replace("N/A", "-1.0") 识别正确的部分,但我正在寻找一种有效的方法来更改原始字符串中的内容?

这似乎有效,有人有什么聪明的吗? LINQ?

Private Sub test()       
Dim input_string As String = "abc:abc:abc:abc:abc:N/A:abc:abc"
        Dim nth_loc As Integer = 5

        Dim ix_s As Integer = IndexOfNth(input_string, ":", nth_loc)
        Dim ix_e As Integer = IndexOfNth(input_string, ":", nth_loc + 1)
        Dim textBefore As String = input_string.Substring(0, ix_s + 1)
        Dim textAfter As String = input_string.Substring(ix_e)
        Dim textbetween As String = input_string.Substring(ix_s + 1, ix_e - ix_s - 1)
        Dim output_string As String = textBefore & textbetween.Replace("N/A", "-1.0") & textAfter
End Sub


    Private Shared Function IndexOfNth(str As String, c As Char, n As Integer) As Integer
            Dim s As Integer = -1

            For i As Integer = 0 To n - 1
                s = str.IndexOf(c, s + 1)

                If s = -1 Then
                    Exit For
                End If
            Next

            Return s
        End Function

【问题讨论】:

  • 你要替换的字符串在第n个位置有关系吗?如果第二个位置有“N/A”,你也不想改变它吗?
  • 不,在这种情况下,我只想更改选择性位置。
  • 首先,您的数据是: 分隔的,而不是制表符分隔的。第二次使用String.Split将字符串拆分成一个数组,改变数组中的第n个项,然后使用String.Join重新组合它。
  • 嗨, : 在这种情况下是为了使调试更容易。 @Matt 感谢 String.Join 函数!

标签: .net vb.net string replace


【解决方案1】:

字符串是不可变的,因此即使使用当前代码也不会修改原始字符串。

“String 对象被称为不可变(只读),因为它的值在创建后无法修改”。 [MSDN : String Class]

因此,我认为使用.Split() 然后.Join() 还是更好:

Dim input_string As String = "abc:abc:abc:abc:abc:N/A:abc:abc"
Dim nth_loc As Integer = 5
Dim split = input_string.Split(":")
split(nth_loc) = "-1.0"
Dim result = String.Join(":", split)

另外,LINQ 是用于查询,而不是数据修改。 LINQ 似乎不适合解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-17
    • 2017-09-17
    • 2021-11-10
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多