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

4

我很新于编程,刚刚开始并学习了一些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
你有考虑使用String.Contains方法吗?https://msdn.microsoft.com/zh-cn/library/dy85x1sa.aspx - Mickey
还有在最后一个 foreach 循环中:如果你将它改成 'if(x != '#') ret += x;',那么你就不需要 else 分支了。 - Mickey
也许可以把它提交到http://codereview.stackexchange.com/? - Euphoric
3个回答

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

这是一个OP的选择问题,signs现在可以是一个由这些字符组成的字符串,即return string.Join("", "!§$%&/()=?".Except(s)) - weston
我认为 string.Concat.Join 更加简洁 https://dev59.com/U2gu5IYBdhLWcg3wAici#11654221 虽然 new String(ret.ToArray()) 也是一种选择,而且更快,同样干净。 - weston

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());
}

0

又一个答案

static string GetUnused(string s)
{
    char[] signs = { '!', '§', '$', '%', '&', '/', '(', ')', '=', '?' };
    var set = new HashSet<char>(signs);

    foreach (char c in s)
        set.Remove(c);

    return string.Concat(set);
}

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);
}

建议您查看 Except 的实现(提示,它使用了一个集合)。 - weston

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接