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 "@".

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

try this one:

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

1 Comment

yes, if you want to remove them i guess Regex will be the best to use.
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?

Comments

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

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.