如何在两个字符串之间替换一个字符串VB

如何在两个字符串之间替换一个字符串VB

本文介绍了如何在两个字符串之间替换一个字符串VB.Net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下字符串

MDSP:TSK:Demo:MDSR:Demo :::: LAT:Test:P:2.3:

现在,我必须将第7个:"和第8个:"之间的LAT替换为ACK.



MDSP:TSK:Demo:MDSR:Demo ::: ACK:Test:P:2.3:


Colud,请让我知道.

I have a string as follows

MDSP:TSK:Demo:MDSR:Demo:::LAT:Test:P:2.3:

Now i have to replace LAT between 7th ":" and 8th ":" to ACK.

i.e.

MDSP:TSK:Demo:MDSR:Demo:::ACK:Test:P:2.3:


Colud you please let me know this.

推荐答案

Dim mystr As String = "MDSP:TSK:Demo:MDSR:Demo:::LAT:Test:P:2.3:"
mystr.Replace("LAT", "ACK")


Dim newParam As String = "ACK"
Dim test As String = "MDSP:TSK:Demo:MDSR:Demo:::LAT:Test:P:2.3:"
Dim nStartExchange As Integer = test.IndexOf("::") + 3
Dim res As String = test.Substring(nStartExchange, test.Length - nStartExchange)
Dim nEndExchange As Integer = res.IndexOf(":"C) + nStartExchange
Dim result As String = test.Substring(0, nStartExchange) & newParam & test.Substring(nEndExchange)
MessageBox.Show(result)


我想您也可以在这种情况下尝试使用正则表达式,但是上面的代码对于您想要修改的字符串非常有效.

另一个可能的解决方案:


I think you could also try using regular expressions in this case, but the above code works quite well for the string that you wanted to modify.

Another possible solution:

Dim newParam As String = "ACK"
Dim test As String = "MDSP:TSK:Demo:MDSR:Demo:::LAT:Test:P:2.3:"
Dim results As String() = test.Split(":"C)
Dim final As String = ""
results(7) = newParam
For i As Integer = 0 To results.Length - 1
    final += results(i)
    If i <> results.Length - 1 Then
        final += ":"
    End If
Next
MessageBox.Show(final)


希望对您有所帮助!


Hope it helps!


Dim str = "MDSP:TSK:Demo:MDSR:Demo:::LAT:Test:P:2.3:"
str = str.Replace("LAT","ACK")



2.如果您想在第7个:"&之间更改字符串第八个:"(如果"LAT"单词未固定可替换."



2. if u want to change string between 7th ":" & 8th ":" (Incase "LAT" word is not fixed for replacement."

Dim str = "MDSP:TSK:Demo:MDSR:Demo:::LAT:Test:P:2.3:"
               Dim colon_start_index = 0
               Dim colon_start_Occurance = 0
               For o As Integer = 0 To str.LastIndexOf(":") - 1
                   If colon_start_Occurance = 7 Then
                       Exit For
                   Else
                       colon_start_index = str.IndexOf(":", colon_start_index) + 1
                       colon_start_Occurance += 1
                   End If
               Next
               str = str.Replace(str.Substring(colon_start_index, str.IndexOf(":", colon_start_index) - (colon_start_index)), "ACK")


祝您编码愉快!
:)


Happy Coding!
:)


这篇关于如何在两个字符串之间替换一个字符串VB.Net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 18:07