StartsWith extension that searches in all words

Is there a StartsWith line extension that it searches at the beginning of every word in the line?

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

I want me to be able to make a predicate for the search.

Let's say there is a list called Faces, ICollection<Person>
Each person has a Name property, with values ​​such as "Ben Stiller" or "Adam Sandler."

I want to be able to do predicates like:

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

Thanks (Other best ways to achieve this are welcome)

+4
source share
5 answers

You can first break the line up with the words:

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

Of course, you could write this as your own extension method, for example:

 public static bool AnyWordStartsWith(this string input, string test) { return input.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries) .Any(x => x.StartsWith(test)); } 
+6
source

Perhaps the most concise approach is to use a regular expression:

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

It is also more reliable than dividing the original string into a character, because it can handle other whitespace characters.

+2
source

Why not create a "ToWords" method and then feed the results of this to StartsWith?

In fact, "ToWords" already exists:

Edit: for a giggle, let it work with brief

  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")); 
+1
source

Well, you can even check it like this:

 bool flag = (sample_str.StartsWith("Sti" ) || sample_str.Contains(".Sti") || sample_str.Contains(" Sti")) 
0
source
  public static bool ContainsWordStartingWith(this string aString, string startingWith) { return aString.Split(' ').Any(w => w.StartsWith(startingWith)); } 
0
source

All Articles