2011-04-20 36 views
0

如何選擇從特定字符數開始的字符串的最後部分。例如,我想在第三個逗號後面顯示所有文本。但我得到一個錯誤,說 「StartIndex不能小於零」。從特定字符數開始的子串

Dim testString As String = "part, description, order, get this text, and this text" 
Dim result As String = "" 
result = testString.Substring(testString.IndexOf(",", 0, 3)) 
+2

你想要的*第三*逗號後面的文本,或*最後一個*逗號後(在給定樣本中恰好相同)?如果你有''一,二,三,四,五,六''的輸入,那麼你的預期結果是什麼? ''四,五,六'「或'五,六」? – 2011-04-20 12:48:17

+0

是在第三個逗號後。我應該把第四個放在那裏,爲了清晰起見,我編輯了它。 – TroyS 2011-04-20 13:00:05

回答

3

繼承人我的兩分錢:

string.Join(",", "aaa,bbb,ccc,ddd,eee".Split(',').Skip(2)); 
+0

正是我在找的東西。它效果很好。謝謝。 – TroyS 2011-04-20 13:21:43

+0

@tmax np,我相信我可以在將來使用它! – Craig 2011-04-20 13:37:52

+0

這很棒,它也幫助我! – Hallaghan 2012-01-03 12:43:48

0

indexOf的第三個參數是要搜索的字符數。您正在尋找,開始於03字符 - 即搜索字符串par爲逗號不存在,所以返回的索引是-1,因此您的錯誤。我認爲你需要使用一些遞歸:

Dim testString As String = "part, description, order, get this text" 
Dim index As Int32 = 0 

For i As Int32 = 1 To 3  
    index = testString.IndexOf(","c, index + 1) 
    If index < 0 Then 
    ' Not enough commas. Handle this. 
    End If 
Next 
Dim result As String = testString.Substring(index + 1) 
+0

我之前就是這樣做的,但是尋找這樣做的一種方法。 – TroyS 2011-04-20 13:17:41

1

替代品(我假設你想最後一個逗號之後的所有文字):

使用LastIndexOf:

' You can add code to check if the LastIndexOf returns a positive number 
Dim result As String = testString.SubString(testString.LastIndexOf(",")+1) 

定期表達式:

Dim result As String = Regex.Replace(testString, "(.*,)(.*)$", "$2") 
+0

第三個逗號後面的所有文字,Dim testString As String =「零件,描述,順序,得到這個文本和這個文本」 – TroyS 2011-04-20 13:16:39

2

代碼「testString.IndexOf(」,「,0,3)」找不到第三個逗號。它從第0位開始查找第一個逗號,查看前三個位置(即字符位置0,1,2)。

如果你想在最後一個逗號後的部分使用是這樣的:

Dim testString As String = "part, description, order, get this text" 
Dim result As String = "" 
result = testString.Substring(testString.LastIndexOf(",") + 1) 

注意+1移動到逗號之後的字符。您應該首先找到索引並添加檢查以確認索引不是-1,索引<也是testString.Length。

0

IndexOf函數僅查找指定字符的「第一個」。最後一個參數(在你的案例3中)指定了要檢查的字符數量,而不是出現的次數。

參考Find Nth occurrence of a character in a string

這裏指定的函數找到一個字符的第N次數。然後使用返回的發生的子字符串函數。

另一種方法是,您也可以使用正則表達式來查找第n個發生。

 
public static int NthIndexOf(this string target, string value, int n) 
    { 
     Match m = Regex.Match(target, "((" + value + ").*?){" + n + "}"); 

     if (m.Success) 
     { 
      return m.Groups[2].Captures[n - 1].Index; 
     } 
     else 
     { 
      return -1; 
     } 
    }
0

我認爲這是你在找什麼

Dim testString As String = "part, description, order, get this text" 
    Dim resultArray As String() = testString.Split(New Char() {","c}, 3) 
    Dim resultString As String = resultArray(2) 
相關問題