在字符串中查找字符串的出现次数

时间:2011-04-30 09:59:08

标签: c#

您在另一个字符串中查找字符串的最快捷,最有效的方法是什么。

例如我有这个文字;

“嘿@ronald和@tom我们这个周末去哪儿了”

但是我想找到以“@”开头的字符串。

由于

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);
}

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分: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?

答案 4 :(得分:-1)

String str = "hallo world"
int pos = str.IndexOf("wo",0)
相关问题