What is the quickest and most efficien开发者_如何学Pythont 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)
精彩评论