2015-11-17 24 views
0

我正在尋找從字符串中提取代碼的基礎上它的屬性。示例'M2.W1.SSE'。我已經通過單詞(代碼)分割字符串,並且正在單獨檢查代碼。但這是我堅持的地方。一種識別字符串中字的方法vb.net

我正在尋找一個單詞,其中包含M作爲起始字母,幷包含2滿員頂部。什麼是最好的方式來做到這一點?我可以通過子字符串來隔離M,但是2個完全停止是我遇到的問題。我只能做一個句號,可能會捕獲其他代碼。

Dim SplitCodes() As String = Split(StringOfCodes, " ") 

    For Each code As String In SplitCodes 
     If code.substring(0,1) = "M" andalso code.Contains(".") = True Then 
      'Delete the code from the string 
     End if 
    Next 
+0

你爲什麼就不能說檢查'code.Contains(「」)' – Rahul

+0

嘗試如果字符串除去第一子後點。如果有,然後做一些事情,並繼續像一個循環可能? – ivan

+0

@Rahul code.contains(「..」)永遠不會匹配,因爲它的代碼看起來像這樣'M2.W1.SSE' – user1500403

回答

0

檢查字符串的長度等於字符串2在此句號已經被替換爲空的長度:

If code.Substring(0, 1) = "M" And Len(Replace(code, ".", "")) = Len(code) - 2 Then 

下面是一個簡單的測試,我放在一起吧:

Dim MyString As String 
    MyString = "M2.W1.SSE" 
    If MyString.Substring(0, 1) = "M" And Len(Replace(MyString, ".", "")) = Len(MyString) - 2 Then 
     TextBox1.Text = MyString 
    Else 
     TextBox1.Text = "Didn't work!!" 
    End If 

的,如果觸發,然後用逗號替換第二句號第一部分引發了其他

您還可以使用分割法來算創建的元素的個數:

Dim MyString As String 
    MyString = "M2.W1.SSE" 
    If MyString.Substring(0, 1) = "M" And Len(Replace(MyString, ".", "")) = Len(MyString) - 2 Then 
     TextBox1.Text = MyString 
    Else 
     TextBox1.Text = "Didn't work!!" 
    End If 
    If code.Substring(0, 1) = "M" And UBound(Split(MyString, ".")) = 2 Then '<-- Option base zero creates 3 elements with the upper one being index 2 
     MsgBox("This method also works") 
    Else 
     MsgBox("This method doesn't work") 
    End If 
+0

謝謝,由於某種原因,我個人更喜歡第二種選擇。 – user1500403

+0

我個人也是如此,我喜歡拆分功能,並且我爲這些類型的東西使用了很多:)。有些人可能會覺得很難理解,所以在這種情況下,其他選項是:) –

0

我最終使用引用的函數類似的方法。我可以想象使用上述建議的代碼來取代計數字符功能。

 If code.Substring(0, 1) = "M" AndAlso CountCharacters(code, ".") = 2 Then 
      'Found 
    Else 
      'Not found 
    End If 


    Public Function CountCharacters(ByVal sString As String, ByVal ch As Char) As Integer 
      Dim cnt As Integer = 0 
      For Each c As Char In sString 
       If c = ch Then cnt += 1 
      Next 
      Return cnt 
     End Function 
+0

爲什麼你會選擇循環,而不是在你的函數分裂?拆分會更有效 –

+0

重新讀取您已經字面上選擇了最低效的方法輪詢字符char –