在字符串中获取未使用的字符?

时间:2016-06-10 12:34:43

标签: c# string chars

我是编程新手,我刚开始学习C#的一些基础知识。我只是尝试编写一个方法来检查字符串中是否包含某些特殊字符。我的结果是这段代码:

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;

但我很确定这不是解决我的问题的好方法......我如何以更优雅的方式解决这个问题呢? 谢谢你的答案。

3 个答案:

答案 0 :(得分:4)

您可以使用Except

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

答案 1 :(得分:0)

如果您将标记存储为list<char>,则可以使用RemoveAll删除方法参数中存在的任何项目,如下所示:

static string getunused(string param)
{
    list<char> signs = new list<char>(){ '!', '§', '$', '%', '&', '/', '(', ')', '=', '?' };
    signs.removeall(c => param.contains((c.tostring())));
    return new string(signs.toarray());
}

答案 2 :(得分:0)

又一个答案

HashSet

static string GetUnused(string s) { char[] signs = { '!', '§', '$', '%', '&', '/', '(', ')', '=', '?' }; var set = new HashSet<char>(signs); foreach (char c in s) { set.Remove(c); if (set.Count == 0) return string.Empty; } return string.Concat(set); } 非常快。

如果输入参数可能非常大,那么下一版本将更有利可图,在某些情况下

{{1}}
相关问题