简体   繁体   中英

finding occurrences of string within a string

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

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

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

try this one:

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM