How can you remove duplicate characters in a string?

前端 未结 20 2286
离开以前
离开以前 2020-12-05 16:39

I have to implements a function that takes a string as an input and finds the non-duplicate character from this string.

So an an example is if I pass string str = \"

20条回答
  •  误落风尘
    2020-12-05 17:12

    I like Quintin Robinson answer, only there should be some improvements like removing List, because it is not necessarry in this case. Also, in my opinion Uppercase char ("K") and lowercase char ("k") is the same thing, so they should be counted as one.

    So here is how I would do it:

    private static string RemoveDuplicates(string textEntered)
        {
    
            string newString = string.Empty;
    
            foreach (var c in textEntered)
            {
                if (newString.Contains(char.ToLower(c)) || newString.Contains(char.ToUpper(c)))
                {
                    continue;
                }
                newString += c.ToString();
            }
            return newString;
        }
    

提交回复
热议问题