C# 如何删除字符串中的重复字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/588774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 09:20:48  来源:igfitidea点击:

How can you remove duplicate characters in a string?

c#

提问by Red Hot

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 = "DHCD" it will return "DHC" or str2 = "KLKLHHMO" it will return "KLHMO"

所以一个例子是,如果我传递字符串 str = "DHCD" 它会返回 "DHC" 或 str2 = "KLKLHHMO" 它会返回 "KLHMO"

采纳答案by CMS

A Linq approach:

Linq 方法:

public static string RemoveDuplicates(string input)
{
    return new string(input.ToCharArray().Distinct().ToArray());
}

回答by Quintin Robinson

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.

我想我在第一次修订时神志不清。

回答by Sparr

For arbitrary length strings of byte-sized characters (not for wide characters or other encodings), I would use a lookup table, one bit per character (32 bytes for a 256-bit table). Loop through your string, only output characters that don't have their bits turned on, then turn the bit on for that character.

对于字节大小字符的任意长度字符串(不适用于宽字符或其他编码),我将使用查找表,每个字符一位(256 位表为 32 字节)。循环遍历您的字符串,仅输出未打开其位的字符,然后打开该字符的位。

string removedupes(string s)
{
    string t;
    byte[] found = new byte[256];
    foreach(char c in s)
    {
        if(!found[c]) {
            t.Append(c);
            found[c]=1;
        }
    }
    return t;
}

I am not good with C#, so I don't know the right way to use a bitfield instead of a byte array.

我不擅长 C#,所以我不知道使用位域而不是字节数组的正确方法。

If you know that your strings are going to be very short, then other approaches would offer better memory usage and/or speed.

如果您知道您的字符串将非常短,那么其他方法将提供更好的内存使用和/或速度。

回答by Chad Birch

It sounds like homework to me, so I'm just going to describe at a high level.

对我来说这听起来像是家庭作业,所以我只是在高层次上进行描述。

  • Loop over the string, examining each character
  • Check if you've seen the character before
    • if you have, remove it from the string
    • if you haven't, note that you've now seen that character
  • 遍历字符串,检查每个字符
  • 检查您之前是否见过该角色
    • 如果有,请将其从字符串中删除
    • 如果你还没有,请注意你现在已经看到了那个角色

回答by mbm

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

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 = '
char* removeDups(const char* str)
{
 char* new_str = (char*)malloc(256*sizeof(char));
 int i,j,current_pos = 0,len_of_new_str;
 new_str[0]='
public String removeDup(String s)
  {
    if(s==null) return null;
    int l = s.length();
    //if length is less than 2 return string
    if(l<2)return s;
    char arr[] = s.toCharArray();

    for(int i=0;i<l;i++)
    {
      int j =i+1; //index to check with ith index
      int t = i+1; //index of first repetative char.

      while(j<l)
      {
        if(arr[j]==arr[i])
        {
          j++;

        }
        else
        {
          arr[t]=arr[j];
          t++;
          j++;
        }

      }
      l=t;
    }

    return new String(arr,0,l);
  }
'; for(i=0;i<strlen(str);i++) { len_of_new_str = strlen(new_str); for(j=0;j<len_of_new_str && new_str[j]!=str[i];j++) ; if(j==len_of_new_str) { new_str[len_of_new_str] = str[i]; new_str[len_of_new_str+1] = '
public static string RemoveDuplicates(string input)
{
    return new string(input.Distinct().ToArray());
}
'; } } return new_str; }
'; return str;

}

}

回答by Tracy

    public static char[] RemoveDup(string s)
    {
        char[] c = new char[s.Length];
        int unique = 0;
        c[unique] = s[0];  // Assume: First char is trivial
        for (int i = 1; i < s.Length; i++)
        {
            if (s[i-1] != s[i]
        c[++unique] = s[i];
        }
        return c;
    }

Hope this helps

希望这可以帮助

回答by Abhishek Jain

My answer in java language.
Posting here so that you might get a idea even it is in Java language.Algorithm would remain same.

我用java语言回答。
在这里张贴,以便您即使是在 Java 语言中也能得到一个想法。算法将保持不变。

String str="AABBCANCDE";  
String newStr=""; 
for( int i=0; i<str.length(); i++)
{
 if(!newStr.contains(str.charAt(i)+""))
 newStr= newStr+str.charAt(i);
 }
 System.out.println(newStr);

回答by V M Rakesh

Revised version of the first answer i.e: You don't need ToCharArray()function for this to work.

第一个答案的修订版,即:您不需要ToCharArray()函数即可工作。

##代码##

回答by yantaq

//this is in C#, validation left out for brevity //primitive solution for removing duplicate chars from a given string

//这是在C#中,为简洁起见省略了验证 //用于从给定字符串中删除重复字符的原始解决方案

##代码##

回答by Madan

##代码##