How can you remove duplicate characters in a string?

前端 未结 20 2233
离开以前
离开以前 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 16:53

    It will do the job

    string removedupes(string s)
    {
        string newString = string.Empty;
        List<char> found = new List<char>();
        foreach(char c in s)
        {
           if(found.Contains(c))
              continue;
    
           newString+=c.ToString();
           found.Add(c);
        }
        return newString;
    }
    

    I should note this is criminally inefficient.

    I think I was delirious on first revision.

    0 讨论(0)
  • 2020-12-05 16:56

    // Remove both upper-lower duplicates

    public static string RemoveDuplicates(string key)
        {
            string Result = string.Empty;
            foreach (char a in key)
            {
                if (Result.Contains(a.ToString().ToUpper()) || Result.Contains(a.ToString().ToLower()))
                    continue;
                Result += a.ToString();
            }
            return Result;
        }
    
    0 讨论(0)
  • 2020-12-05 16:57
        void removeDuplicate()
        {
          string value1 = RemoveDuplicateChars("Devarajan");
        }
    
         static string RemoveDuplicateChars(string key)
        {
            string result = "";          
            foreach (char value in key)
                if (result.IndexOf(value) == -1)                   
                    result += value;
            return result;
        }
    
    0 讨论(0)
  • 2020-12-05 16:57

    char *remove_duplicates(char *str) { char *str1, *str2;

    if(!str)
        return str;
    
    str1 = str2 = str;
    
    while(*str2)            
    {   
        if(strchr(str, *str2)<str2)
        {
            str2++;
            continue;
        }
    
        *str1++ = *str2++;      
    }
    *str1 = '\0';
    
    return  str;
    

    }

    0 讨论(0)
  • 2020-12-05 16:58

    Not sure how optimal it is:

    public static string RemoveDuplicates(string input)
    {
        var output = string.Join("", input.ToHashSet());
        return output;
    }
    
    0 讨论(0)
  • 2020-12-05 16:59
    var input1 = Console.ReadLine().ToLower().ToCharArray();
    var input2 = input1;
    var WithoutDuplicate = input1.Union(input2);
    
    0 讨论(0)
提交回复
热议问题