2016-06-10 94 views
3

我對編程真的很陌生,我剛開始學習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/en-us/library/dy85x1sa.aspx – Mickey

+0

也在最後一個foreach循環中:如果將其更改爲'if(x!='#')ret + = x;'那麼你將不需要else路徑。 – Mickey

+0

也許把它帶到http://codereview.stackexchange.com/? – Euphoric

回答

4

你可以使用Except

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

關於OP選擇的問題,'signs'現在可以是這些字符的'string',即'return string.Join(「,」!!$%&/()=?「。除了(s))' – weston

+0

我認爲'string.Concat'甚至比'.Join'更乾淨http://stackoverflow.com/a/11654221/360211雖然'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); 
} 
+0

建議你看看['Except']的實現(http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,e289e6c98881b2b8)(提示,它使用一組) – weston

+0

@weston - 好,謝謝。 –