How to Replace any of these “/ \\ [ ] : | < > + = ; , ? *” Characters in a string with empty string in asp.net

元气小坏坏 提交于 2019-12-25 05:45:10

问题


I would like to replace any of the below occurrence of characters in a string with empty string in asp.net c# "/ \ [ ] : | < > + = ; , ? *"

i am trying to replace it with

mystring.contains('[')
 {
 mystring.Replace('[',' ');
 }

Currently i am doing it as above . Is there a cleaner way of doing this. Thanks and Regards


回答1:


There are many ways:

1) via regex:

var pattern = @"[\/\\[\]\:\|\<>\+\=\;\,\?\*]";
var sample = "test * beacuse [a]";
var result = Regex.Replace(sample, 
                           pattern, 
                           string.Empty, 
                           RegexOptions.CultureInvariant);

2) via linq:

var pattern = @"/\[]:|<>+=;,?*";
var result = new string(sample.Where(ch => !pattern.Contains(ch)).ToArray());

3) via StringBuilder:

var sb = new StringBuilder();

foreach (char t in sample)
{
    if (!pattern2.Contains(t))
    {
        sb.Append(t);
    }
}

result = sb.ToString();

These ways are only samples ;)




回答2:


You can use a simple loop and you don't need to check first if it contains it at all:

foreach(char c in @"/\[]:|<>+=;,?*")
    mystring = mystring.Replace(c, ' ');

This replaces all occurences with a space similar to your code. If you instead want to replace it with an empty string (as mentioned) you can use this:

foreach(char c in @"/\[]:|<>+=;,?*")
    mystring  = mystring.Replace(c.ToString(), "");

You could improve it a little bit by doing the replaces with a System.Text.StringBuilder:

StringBuilder sb = new StringBuilder(mystring);
foreach (char c in @"/\[]:|<>+=;,?*")
    sb.Replace(c.ToString(), "");
mystring = sb.ToString();

The StringBuilder is not necessarily more performant in terms of CPU cycles but in terms of memory consumption since it doesn't create always new instances.




回答3:


You can use regular expression as mention by @ThreeFx. Another trick is to split the string and re-join it afterwards:

var toBeRemoved = new char[] { '[', ']', '/', '\\', ':', '|', '<', '>', '+', '=', ';', ',', '?', '*' };
mystring = string.Join(string.Empty, mystring.Split(toBeRemoved));



回答4:


You could write a simple extension method if you find yourself needing to remove chars from strings like this fairly often:

public static class StringExt
{
    public static string Remove(this string self, params char[] charsToRemove)
    {
        var result = new StringBuilder();

        foreach (char c in self)
            if (Array.IndexOf(charsToRemove, c) == -1)
                result.Append(c);

        return result.ToString();
    }

This should be fairly efficient.

By using a params argument, we have a couple of ways to call it, as demonstrated by this sample code:

string test = @"a/b\c[d]e:f|g<h>i+j=k;l,m?n*o";

// Pass an array of chars to remove:
string result1 = test.Remove(@"/\[]:|<>+=;,?*".ToCharArray());
Console.WriteLine(result1);

// Pass individually listed chars to remove:
string result2 = test.Remove('/', '\\', '[', ']', ':', '|', '<', '>', '+', '=', ';', ',', '?', '*');
Console.WriteLine(result2);


来源:https://stackoverflow.com/questions/25154701/how-to-replace-any-of-these-characters-in-a-strin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!