4

Is there an extension of string's StartsWith that it searches at the start of every word in the string?

Something like: "Ben Stiller".StartsWithExtension("Sti") returning true

I want this so I can make a predicate for searching.

Lets say there's a list called Persons, ICollection<Person>
Each person has a property Name, with values like "Ben Stiller" or "Adam Sandler".

I want to be able to do predicates like:

Persons.Where(p => p.Name.StartsWithExtension(query))

Thanks (Other better ways of achieving this are welcome)

4

5 回答 5

6

You can split the string up by words first, like this:

var result = "Ben Stiller".Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                          .Any(x => x.StartsWith("Sti"));

Of course you could write this as you're own extension method, like this:

public static bool AnyWordStartsWith(this string input, string test)
{
    return input.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
                .Any(x => x.StartsWith(test));
}
于 2013-03-30T19:04:09.413 回答
2

Probably the most succinct approach is to use regex:

public static bool StartsWithExtension(this string value, string toFind)
{
    return Regex.IsMatch(value, @"(^|\s)" + Regex.Escape(toFind));
}

This is also more reliable than splitting the source string on the character ' ', since it can handle other whitespace characters.

于 2013-03-30T19:10:33.623 回答
1

Why not instead create a "ToWords" method, then feed the results of that to StartsWith?

In fact, "ToWords" already kind of exists:

Edit: for giggles, let's have it work on multiples

 var someNames = new []{ "Sterling Archer", "Cyril Figgus" };
 var q = someNames
    .Select(name => name.Split(' '))
    .SelectMany( word => word)
     // the above chops into words
    .Where(word => word.StartsWith("Arch"));
于 2013-03-30T19:04:12.983 回答
0

Well you can even check it this way :

bool flag = (sample_str.StartsWith("Sti" ) || sample_str.Contains(".Sti") || sample_str.Contains(" Sti")) 
于 2013-03-30T19:07:43.110 回答
0
    public static bool ContainsWordStartingWith(this string aString, string startingWith)
    {
        return aString.Split(' ').Any(w => w.StartsWith(startingWith));
    }
于 2013-03-30T19:22:41.017 回答