简体   繁体   English

从字符串C#中删除特定字符

[英]Remove specific characters from string C#

I have got a string ["foo","bar","buzz"] from view, i want to remove [ , " &, ] 我从视图中得到了一个字符串["foo","bar","buzz"] ,我想删除[" &, ]
I have used string x = tags.Trim(new Char[] { '[', '"', ']' }); but the output i got is foo","bar","buzz instead of foo,bar,buzz 我使用了string x = tags.Trim(new Char[] { '[', '"', ']' });但是我得到的输出是foo","bar","buzz而不是foo,bar,buzz

在此处输入图片说明

I have tried Trimming & this but still having problem. 我已经尝试过修剪这个,但是仍然有问题。

As alternative, you can use a "simple" Replace 作为替代,您可以使用“简单” Replace

string x = tags.Replace("[","")
               .Replace("\"","")
               .Replace("]","");

It isn't fast, but it's simple. 它不是很快,但是很简单。

If you need more performance you should use an alternative. 如果需要更高的性能,则应使用替代方法。


please note: that each Replace call returns a new string, and with every call the whole string is reevaluated. 请注意:每个Replace调用都会返回一个新字符串,并且每次调用都会重新评估整个字符串。 Although I often use this myself (due to the readability) it's not recommended for complex patterns or very long string values 尽管我经常(出于可读性)自己使用此代码,但不建议将其用于复杂的模式或非常长的字符串值

正则表达式的力量!

var x = Regex.Replace(tags, @"(\[|""|\])", "");

Personally, I'd switch your order of operations. 就个人而言,我会切换您的操作顺序。 For instance 例如

String[] unformattedTags = tags.Split(',');
String[] formattedTags = unformattedTags.Select(itm => itm.Trim( '[','"',']')).ToArray();

This removes the restricted characters from each tag individually. 这样可以分别从每个标签中删除受限字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM