如何从动态字符串内容中获取修复子字符串?

时间:2013-04-09 10:13:53

标签: vb.net vb.net-2010

我正在开发VB.NET Windows应用程序。在VS 2010中。

我想获得子串

  

$ CostCenterId | 4 ^ 10

从下面的字符串。

  

PaymentMode | NEFT ^ $ IsPaid |虚假^ $货币| INR印   卢比^ $ CostCenterId | 4 ^ 10 $ LedgerId | 2 ^ 3 $

序列中当前字符串($ CostCenterId | 4 ^ 10)的位置可能会发生变化。 但它总会在两个$符号之间。 我写了下面的代码,但是混淆了下一步要写什么?

Public Sub GetSubstringData()

   dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian  
    Rupee^$CostCenterId|4^10$LedgerId|2^3$"

     Dim CostIndex As Integer
     CostIndex = sDiscription.IndexOf("CostCenterId")
     sDiscription.Substring(CostIndex,

    End Sub

6 个答案:

答案 0 :(得分:3)

查看字符串的Split function。这允许您根据指定的分隔符将字符串拆分为子字符串。

然后你可以这样做:

Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"
Debug.WriteLine("$" + sfullString.Split("$"c)(3))

结果:$CostCenterId|4^10

您可能希望进行一些错误检查,以确保字符串实际上包含您期望的数据。

然而,查看数据时,您所拥有的是包含键值对的字符串,因此您最好拥有一个属性来保存CostCenterId并提取如下数据:

Public Property CostCenterId As String

Public Sub Decode(ByVal code As String)
    For Each pair As String In code.Split("$"c)
        If pair.Length > 0 AndAlso pair.Contains("|") Then
            Dim key As String = pair.Split("|"c)(0)
            Dim value As String = pair.Split("|"c)(1)
            Select Case key
                Case "CostCenterId"
                    Me.CostCenterId = value
            End Select
        End If
    Next
End Sub

然后这样称呼:

Decode("PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$")

答案 1 :(得分:0)

为什么不将$()拆分()到一个数组中,然后查找包含CostCenterId的元素

答案 2 :(得分:0)

尝试这样的事情:

Dim CostIndex As Integer
CostIndex = sDiscription.IndexOf("CostCenterId")

auxNum = sDiscription.IndexOf("$"c, CostIndex) - CostIndex
sResult = sDiscription.SubString(CostIndex, auxNum)

答案 3 :(得分:0)

这应该有效:

Dim token = "$CostCenterId"
Dim costIndexStart As Integer = sfullString.IndexOf(token)
Dim costIndexEnd As Integer = sfullString.IndexOf("$", costIndexStart + token.Length)
Dim cost As String = sfullString.Substring(costIndexStart, costIndexEnd - costIndexStart + 1)

结果:"$CostCenterId|4^10$"

如果你想省略美元符号:

Substring(costIndexStart + 1, costIndexEnd - costIndexStart - 1)

答案 4 :(得分:0)

你的字符串,

Dim xString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian Rupee^$CostCenterId|4^10$LedgerId|2^3$"

子串过程,

 xString = xString.Substring(xString.IndexOf("$CostCenter"), xString.IndexOf("$", xString.IndexOf("$CostCenter") + 1) - xString.IndexOf("$CostCenter"))

答案 5 :(得分:0)

试用此代码:

  Dim sfullString = "PaymentMode|NEFT^$IsPaid|False^$Currency|INR-Indian" _
    & "Rupee^$CostCenterId|4^10$LedgerId|2^3$"

        Dim sp() As String = {"$"}
        Dim ar() As String = sfullString.Split(sp, StringSplitOptions.RemoveEmptyEntries)
        Array.Sort(ar)
        MsgBox("$" & ar(0))