我有一個字符串,例如「這是一個示例」。在這個句子中是另一個詞 - 「一個小測試」。我想知道這句話有多少次是「小測試」。有什麼辦法嗎?由於獲取多個包含的總和
string tmp = "This a little test is a little test an example. a little test";
int sum = ...... (the count of "a little test")
我有一個字符串,例如「這是一個示例」。在這個句子中是另一個詞 - 「一個小測試」。我想知道這句話有多少次是「小測試」。有什麼辦法嗎?由於獲取多個包含的總和
string tmp = "This a little test is a little test an example. a little test";
int sum = ...... (the count of "a little test")
你可以這樣做:
int sum = Regex.Matches(tmp, "a little test").Count;
如果能在正則表達式中使用「搜索術語」可能包含的字符,你可能需要使用Regex.Escape
:
int sum = Regex.Matches(tmp, Regex.Escape(@"my search term with $pecia| $ymb\0Ls")).Count;
輝煌。 +1。另外(進一步閱讀):http://cc.davelozinski.com/c-sharp/c-net-fastest-way-count-substring-occurrences-string –
@JᴀʏMᴇᴇ偉大的鏈接! – Jcl
可能的重複[你將如何計算一個stri ng在一個字符串?](http://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-within-a-string) – hellow
@cookiesoft雖然標題的介紹問題可能暗示,否則,實際問題(以及接受的答案)是針對字符串中單個字符的出現,這不是OP要求的問題。 – Jcl
請參閱[「應該問題是否在其標題中包含」標記?「]( http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles),其中的共識是「不,他們不應該」! –