Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String cleaning and formatting

Tags:

c#

asp.net

I have a URL formatter in my application but the problem is that the customer wants to be able to enter special characters like:

: | / - “ ‘ & * # @

I have a string:

string myCrazyString  = ":|/-\“‘&*#@";

I have a function where another string is being passed:

public void CleanMyString(string myStr)
{
} 

How can I compare the string being passed "myStr" to "myCrazyString" and if "myStr has any of the characters in myCrazyString to remove it?

So if I pass to my function:

"this ' is a" cra@zy: me|ssage/ an-d I& want#to clea*n it"

It should return:

"this is a crazy message and I want to clean it"

How can I do this in my CleanMyString function?

like image 635
user710502 Avatar asked Sep 01 '26 23:09

user710502


2 Answers

Use Regular Expression for that Like:

pattern = @"(:|\||\/|\-|\\|\“|\‘|\&|\*|\#|\@)";

System.Text.RegularExpressions.Regex.Replace(inputString, pattern, string.Empty);
  • split each string you want to remove by |
  • To remove the special characters like the | itself use \, so \| this will handle the | as normal character.

Test:

inputString = @"H\I t&he|r#e!";
//output is: HI there!
like image 117
Jalal Said Avatar answered Sep 03 '26 15:09

Jalal Said


solution without regular expressions, just for availability purposes:

    static string clear(string input)
    {
        string charsToBeCleared = ":|/-\“‘&*#@";
        string output = "";
        foreach (char c in input)
        {
            if (charsToBeCleared.IndexOf(c) < 0)
            {
                output += c;
            }
        }
        return output;
    }
like image 31
besamelsosu Avatar answered Sep 03 '26 14:09

besamelsosu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!