我有一组switch-case语句,例如“你好,你怎么样”,“嗨,我能帮你什么忙?”。如果用户输入的是逐字逐句的,即:“你好,你怎么样”,匹配就有效。
但如果用户输入“你好,你怎么样”,但大小写不同,匹配将失败。
如果用户的输入是相同的但大小写不同,则应该匹配。
"Hello, how are you" == "Hello, How are You" == "HELLO, how are YOU"
这该怎么做呢?
模式匹配
和switch..case
。string a = "Hello, How are You";
switch (a)
{
case string str when str.Equals("hello, how are you", StringComparison.InvariantCultureIgnoreCase):
// Your code
break;
default:
// default code
break;
}
case string
类型检查是多余的,因为它已经知道 a
是一个字符串,所以你可以说 case {}
(非空)如果你想的话。我不知道编译器是否会优化掉第二次检查。希望在某个时候,当类型已知时,C# 能够得到类似 case _ str when...
这样的东西。 - undefined只需在所有内容上使用 ToLower
进行非区分大小写的转换:
switch (myString.ToLower())
{
case "hello, how are you":
// do something
break;
}
switch
处理程序仅限于精确字符匹配。最终有三种方法:
if
而不是switch
,并利用手动字符串相等性测试 - 可能指定StringComparison
以进行大小写不敏感性ToLower[Invariant]
,并消耗分配when
的switch
表达式实际上与一系列if
、else
测试没有什么不同——只是为了符合switch
语法而硬塞进去... - Marc Gravell不要将两个字符串都转换为大写或小写,然后再进行比较,而应该使用可以忽略大小写的相等比较。例如:
String string1 = "Hello, how are you";
if (string1.Equals("Hello HOW are you", StringComparison.OrdinalIgnoreCase))
{
...
}
You should consider carefully exactly which rules are appropriate - ordinal, the current culture, the invariant culture, or possibly another culture entirely (e.g. using StringComparer.Create(culture, true)).
switch (yourValue.ToLower())
,那么 switch 外部的代码不会受到 ToLower 的影响 - 不过这并不一定是一个好的做法;我只是想说“因为它们在 UI 的其他地方显示”是无关紧要的。 - Marc Gravell