2011-04-30 50 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?

相关问题