C#字符串比较由于其中包含特殊字符的字符串而失败

编程入门 行业动态 更新时间:2024-10-26 18:27:03
本文介绍了C#字符串比较由于其中包含特殊字符的字符串而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个字符串列表,其中包含一些带有特殊字符(例如-,[,],(,)的字符串).

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#字符串比较由于其中包含特殊字符的字符串而失败

本文发布于:2023-10-13 17:12:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1488587.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   其中包含   特殊字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!