C#字符串比较由于其中包含特殊字符的字符串而失败 [英] C# String comparison fails for string having special character in it
问题描述
我有一个字符串列表,其中包含一些带有特殊字符(例如-,[,],(,)的字符串).
I have a list of string that contains few strings with some special characters like -, [, ], (, ).
我正在将字符串传递给需要解析以上列表和方法的方法.查找是否找到完全匹配的内容.
I am passing a string to a method where I need to parse the above list & find if the exact match is found or not.
为此,我编写了以下代码,但是当字符串中出现特殊字符时,就无法进行比较.
For this I have written the below code, but when ever the special characters are present in the string, its not able to compare.
foreach (var item in myList)
{
if (myInput.Trim().ToUpper() == item.Trim().ToUpper() ) //Here myInput is "In - Com [SP]"
{
count++;
}
}
但是,如果我通过前面的@符号比较静态字符串,则比较工作正常.例如:
But if I compare a static string by a preceding @ symbol, then the compare is working fine. For Example :
if (item == @"In - Com [SP]")
{
count++;
}
有人可以帮助我如何将其合并为动态字符串列表吗?注意:我们不能将@与字符串变量连接.
Can anyone please help me how to incorporate this for a dynamic list of strings? NB : We cant concatenate @ with a string variable.
使用Regex存在任何方式吗?
Any ways exist by using Regex?
推荐答案
如果要计数,只需 Count()
借助 Linq 即可;要测试字符串是否相等,请使用 String.Equals
:
If you want to count, just Count()
with a help of Linq; to test if strings are equal use String.Equals
:
System.Linq;
...
// do not do Trim() repeatedly
String testValue = myInput.Trim();
int count = myList
.Count(item => String.Equals(item.Trim(),
testValue,
StringComparison.OrdinalIgnoreCase));
这篇关于C#字符串比较由于其中包含特殊字符的字符串而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!