2011-04-30 53 views
1

嗨在另一個字符串中查找字符串的最快和最有效的方式是什麼?在字符串中發現字符串的出現

例如,我有這個文本;

「嘿@ronald和@湯姆我們要去哪裏這個週末」

但是我想找到與開始字符串「@」。

感謝

回答

3

您可以使用正則表達式。

string test = "Hey @ronald and @tom where are we going this weekend"; 

Regex regex = new Regex(@"@[\S]+"); 
MatchCollection matches = regex.Matches(test); 

foreach (Match match in matches) 
{ 
    Console.WriteLine(match.Value); 
} 

將輸出:

@ronald 
@tom 
+0

+1爲最可重複使用的解決方案imo – Nicolas78 2011-04-30 10:11:30

+0

感謝這爲我工作 – pmillio 2011-04-30 10:50:52

-1
String str = "hallo world" 
int pos = str.IndexOf("wo",0) 
+0

標籤檢查是C#.. – Homam 2011-04-30 10:03:08

+0

謝謝,我糾正我的職務。 – 2011-04-30 10:03:56

+0

仍然問題是如果您期望多於一場比賽,那麼該怎麼辦?正如示例中那樣 - 效率在 – Nicolas78 2011-04-30 10:10:36

0

試試這個:

string s = "Hey @ronald and @tom where are we going this weekend"; 
var list = s.Split(' ').Where(c => c.StartsWith("@")); 
+0

中踢的位置該字可能以點或逗號結尾,對嗎? – Homam 2011-04-30 10:10:10

+0

是的,如果你想刪除它們,我猜'正則表達式將是最好的使用。 – mBotros 2011-04-30 10:12:04

1

你需要使用正則表達式:

string data = "Hey @ronald and @tom where are we going this weekend"; 

var result = Regex.Matches(data, @"@\w+"); 

foreach (var item in result) 
{ 
    Console.WriteLine(item); 
} 
0

如果你是速度之後:

string source = "Hey @ronald and @tom where are we going this weekend"; 
int count = 0; 
foreach (char c in source) 
    if (c == '@') count++; 

如果你想要一個班輪:

string source = "Hey @ronald and @tom where are we going this weekend"; 
var count = source.Count(c => c == '@'); 

這裏How would you count occurrences of a string within a string?

相關問題