// Split the word by space
var split = str.Split(" ");
// Check if firstname or lastname starts with searchString
var found = split[0].StartsWith(searchString) || split[1].StartsWith(searchString);
如果您不知道此人是否也有中间名,并且您也希望对此进行测试:
var searchString = "Sam";
var split = customerName.Split(" ");
var found = false;
foreach(var str in split)
{
found == found || str.StartsWith(searchString);
if(found)
break;
}
将其包装在一个方法中:
public bool NameStartsWith(string name,string searchStr)
{
var split = name.Split(" ");
foreach(var str in split)
{
if(str.StartsWith(searchString))
return true;
}
return false;
}
像这样使用它:
var matches = NameStartsWith("Sameer Singh","Sa"); // true
var matches = NameStartsWith("Sameer Singh","Si"); // true
var matches = NameStartsWith("Sameer Singh","S"); // true
var matches = NameStartsWith("Bobby Singer Bobberson","Sing"); // true
var matches = NameStartsWith("Sameer Singh","meer"); // false