gpt4 book ai didi

c# - 根据c#中每个单词的开头搜索字符串

转载 作者:行者123 更新时间:2023-11-30 20:04:19 31 4
gpt4 key购买 nike

我想从任何列的任何单词开始搜索关键字。

例如,displayedCustomers 对象包含 Name,即 Sameer Singh。

所以当我的搜索变量

searchOption="eer" //it should not search, 
searchOption="ingh" //it should not search,
searchOption="Sa" //it should search,
searchOption="Si" //it should search,
searchOption="ameer" //it should not search

我之前将此代码用于整个单词。但不知道拆分字符串的空间并与起始元素进行比较。请帮助以有效的方式做到这一点

最佳答案

// 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

关于c# - 根据c#中每个单词的开头搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13154061/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com