我有
public readonly IEnumerable<string> QuestionStrings = new List<string>
{
// okay?,are you okay?,what to do?
};
我正在读取用户的输入,如果输入与上面列出的问题之一匹配,我想向用户发送特定的消息。
我的问题是我希望比较不区分大小写和问号。
因此,如果用户输入“好吗?”,“好吗?”,“好还是好”,我想将所有这些消息都一样对待,并将相同的特定消息发送给用户
我能够比较不区分大小写的字符串
QuestionStrings.Contains(userInput, StringComparer.OrdinalIgnoreCase);
但是我找不到忽略问号的方法
有什么办法吗? “除了检查用户输入的末尾是否包含?之外,”
答案 0 :(得分:1)
除了忽略它们外,您还可以将它们从列表的第一位删除,并在比较时从输入字符串中将它们删除:
public readonly IEnumerable<string> QuestionStrings = new List<string>
{
"okay",
"are you okay",
"what to do"
};
...
QuestionStrings.Contains(userInput.Replace('?', ''), StringComparer.OrdinalIgnoreCase);
如果您坚持要在列表中保留问号,则另一个选择是使用Any
而不是Contains
-这将允许您使用lambda表达式执行比较:>
QuestionStrings.Any(s => s
.Replace('?', '')
.Equals(userInput.Replace('?', ''), StringComparison.OrdinalIgnoreCase));
答案 1 :(得分:1)
一种灵活且富有表现力的代码方法是,使用一系列正则表达式(可能存储在资源表或数据库中)定义需求,然后将其直接转换为运行时逻辑。
初始化:
//In a practical application you would load this from a resource or database
List<string> QuestionStrings = new List<string>
{
"^okay.$", //Can appear anywhere in string with or without question mark
"are you okay.", //Must be the entire string, with or without question mark
"^what to do\?" //Question mark is required
};
var regexs = QuestionStrings.Select( s => new RegEx(s) ).ToList();
然后,在您输入用户信息后,检查匹配项:
var match = regexs.Any( x => x.IsMatch( userInput ) );
答案 2 :(得分:0)
您可以尝试以下方法:
QuestionStrings.Contains(userInput.Replace("?","").Trim(), StringComparer.OrdinalIgnoreCase);
答案 3 :(得分:0)
您可以使用此处提到的内容:https://stackoverflow.com/a/368850/8233385 目的是解析字符串中的每个字符,以便仅将a个字符转换为z个字符