2013-04-09 54 views
1

我正在開發VB.NET窗口應用程序。在2010年VS如何從動態字符串內容獲取修復子字符串?

我想要得到的子

$ CostCenterId | 4^10

從下面的字符串。

PaymentMode | NEFT^$ IsPaid |虛假^ $貨幣| INR印 盧比^ $ CostCenterId | 4^$ 10 LedgerId | 2^3 $

當前字符串的位置($ CostCenterId | 4^10)的順序可能會改變。 但它會始終在兩個$符號之間。 我已經寫了下面的代碼,但感到困惑abt接下來要寫什麼?

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 

回答

0

爲什麼不$分裂()將字符串到一個數組,然後尋找其中包含CostCenterId

0

嘗試是這樣的元素:

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

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

「$」c的用法是什麼? – bnil 2013-04-09 10:22:26

+0

'c'表示左邊的字符必須被視爲字符而不是字符串。 VB.NET的方式是直接放置字符。如果你願意,你可以在沒有這個的情況下使用它,像String一樣對待它,它的工作原理是一樣的。 – SysDragon 2013-04-09 10:25:59

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$") 
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) 

[R esult:"$CostCenterId|4^10$"

如果你想省略美元的跡象:

Substring(costIndexStart + 1, costIndexEnd - costIndexStart - 1) 
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")) 
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)) 
相關問題