1

What is the quickest and most efficient way of finding a string within another string.

For instance I have this text;

"Hey @ronald and @tom where are we going this weekend"

However I want to find the strings which start with "@".

Cœur
  • 37,241
  • 25
  • 195
  • 267
pmillio
  • 1,089
  • 2
  • 13
  • 20

5 Answers5

4

You can use Regular expressions.

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);
}

That will output:

@ronald
@tom
Episodex
  • 4,479
  • 3
  • 41
  • 58
1

You need to use Regular Expressions:

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);
}
Homam
  • 23,263
  • 32
  • 111
  • 187
0

try this one:

string s = "Hey @ronald and @tom where are we going this weekend";
var list = s.Split(' ').Where(c => c.StartsWith("@"));
Maged Samaan
  • 1,742
  • 2
  • 19
  • 39
0

If you are after speed:

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

If you want a one liner:

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

Check here How would you count occurrences of a string within a string?

Community
  • 1
  • 1
Ian G
  • 29,468
  • 21
  • 78
  • 92
-1
String str = "hallo world"
int pos = str.IndexOf("wo",0)
Richard Brightwell
  • 3,012
  • 2
  • 20
  • 22
  • still the question is what to do if you expect more than one match, as in the example - that's where the efficiency kicks in – Nicolas78 Apr 30 '11 at 10:10