Reputation: 172378
I want to extract unique characters from a string. For example:- 'AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ'
will return 'ABCFGDJ'
I have tried below piece of code but now I want to optimize it. Please suggest if anyone knows.
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;
}
Upvotes: 7
Views: 7894
Reputation: 6591
if "AAABBBAAA" should return "ABA", then the following does it. Albeit not very fast.
List<char> no_repeats = new List<char>();
no_repeats.Add(s[0]);
for (int i = 1; i < s.Length; i++)
{
if (s[i] != no_repeats.Last()) no_repeats.Add(s[i]);
}
string result = string.Join("", no_repeats);
Upvotes: 2
Reputation: 23833
Try this
string str = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";
string answer = new String(str.Distinct().ToArray());
I hope this helps.
Upvotes: 2
Reputation: 1499800
Another LINQ approach, but not using string.Join
:
var result = new string(original.Distinct().ToArray());
I honestly don't know which approach to string creation would be faster. It probably depends on whether string.Join
ends up internally converting each element to a string before appending to a StringBuilder
, or whether it has custom support for some well-known types to avoid that.
Upvotes: 5
Reputation: 48558
How about
var result = string.Join("", "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ".Distinct());
Make sure that you include System.Linq
namespace.
Upvotes: 2
Reputation: 116098
I don't know if this is faster, but surely shorter
string s = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";
var newstr = String.Join("", s.Distinct());
Upvotes: 14