2013-01-31 28 views
1

嗨,我有一個字符串「abc%d ef%g hi%j」。我想獲得「%」的索引。它應該給出第一次出現的索引,即3。有人可以給我一個這樣的C#代碼片段嗎?C#獲取子串的第一個出現索引

預先感謝

+3

whathaveyoutried.com String.IndexOf( '%') – Alex

+3

爲什麼3?因爲我在%之前看到空間,應該是4? –

+0

好4.但我得到-1。我認爲這是多重冤枉。 –

回答

4

的片段是:

int firstOccurence = "abc %d ef %g hi %j".IndexOf("%"); 
// firstOccurence will be 4 
+0

它會給出第一個出現的索引嗎?它給-1。 –

+0

呃,我更新了這篇文章。 – Jason

3

返回將是4 C#的索引是具有從零開始的索引。

string foo = "abc %d ef %g hi %j"; 
int i = foo.IndexOf("%"); // Returns 4 

資源:

退房String.IndexOf() on MSDN

注:

請你和青睞和審查whathaveyoutried.com StackOverflow上的FAQ's。它會讓你的體驗更加有趣!

0
string x = "bc %d ef %g hi %j"; 
int y = x.IndexOf('%'); 
0

LINQ的版本

string str = "abc %d ef %g hi %j"; 
var ind = str.Select((item, index) => new { Found = item, Index = index }).Where(it => it.Found=='%').Select(it => it.Index).First(); 
相關問題