简体   繁体   English

如何从字符串中提取唯一字符?

[英]How do I extract unique characters from a string?

I have a string, "aabbcccddeefddg", and I want to extract the unique characters from it. 我有一个字符串“ aabbcccddeefddg”,我想从中提取唯一字符。 The result set should be "abcdefg". 结果集应为“ abcdefg”。

Note : I don't want to use the String.Distinct function in C#. 注意 :我不想在C#中使用String.Distinct函数。

Not sure why you don't want to use Distinct , but here's a solution using a HashSet<char> : 不知道为什么不想使用Distinct ,但是这是一个使用HashSet<char>的解决方案:

HashSet<char> chars = new HashSet<char>();
string s = "aabbcccddeefddg";
foreach(char c in s)
{
    chars.Add(c);
}

foreach(char c in chars)
{
    Console.WriteLine(c);
}

How about this: 这个怎么样:

static string extract(string original)
        {
            List<char> characters = new List<char>();
            string unique = string.Empty;

            foreach (char letter in original.ToCharArray())
            {
                if (!characters.Contains(letter))
                {
                    characters.Add(letter);
                }
            }

            foreach (char letter in characters)
            {
                unique += letter;
            }

            return unique;
}

Check out the pseudo code below 查看下面的伪代码

initialize array index[256] to 0

for (i=0; i<length_of_string; i++)
{
  index[string[i]]++;
}

for (i=0; i<256; i++)
{
  if (index[i] > 0)
    print ascii of **i** 
}

UPDATE 更新

The below loop will print the characters in the order in which it appeared in the original string. 下面的循环将按照在原始字符串中出现的顺序打印字符。

for (i=0; i<256; i++)
{
  if (index[i] > 0)
  {
    index[i] = 0
    print ascii of **i**
  }
}
string s = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";

var newstr = String.Join("", s.Distinct());

Or split the string into an array of chars. 或将字符串拆分为字符数组。 Then loop through it. 然后循环遍历。 Take the remainder (everything after the current letter) of the string (with substring) and use String.Replace on it to remove other references of the same letter. 取字符串(带子字符串)的其余部分(当前字母之后的所有内容),然后使用String.Replace对其进行删除,以删除同一字母的其他引用。 Then concatenate the result back with the first part. 然后将结果与第一部分连接起来。 Do this for every letter. 每个字母都要这样做。

Problem also solved. 问题也解决了。

Does this help? 这有帮助吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM