Search code examples
c#stringchars

Get unused chars in string?


I am really new to Programming and I just started and learned some basics for C#. I just tried to write a method that checks if some special chars are NOT included in a string. My result is this code:

static string GetUnused(string s)
{
    /*
     *  Propably will get confused if s contains '#' char... how2fix?
     */
    char[] signs = { '!', '§', '$', '%', '&', '/', '(', ')', '=', '?' };
    foreach (char c in s)
    {
        if (c == '!') signs[0] = '#';
        if (c == '§') signs[1] = '#';
        if (c == '$') signs[2] = '#';
        if (c == '%') signs[3] = '#';
        if (c == '&') signs[4] = '#';
        if (c == '/') signs[5] = '#';
        if (c == '(') signs[6] = '#';
        if (c == ')') signs[7] = '#';
        if (c == '=') signs[8] = '#';
        if (c == '?') signs[9] = '#';
    }
    string ret = string.Empty;
    foreach (char x in signs)
    {
        if (x == '#') ret += "";
        else ret += x;
    }
    return ret;

but I am pretty sure that is not a good solution to my Problem... How do I mange to solve this in a more elegant way? Thank you for your Answers.


Solution

  • You could use Except:

    private static string GetUnused(string s)
    {
        char[] signs = {'!', '§', '$', '%', '&', '/', '(', ')', '=', '?'};
        var ret = signs.Except(s);
        return String.Join("",ret);
    }