According to my understanding, you want to eliminate duplicates only if it is in a consecutive sequence. You could achieve it using the following
Using List<string>
var nonDuplicates = new List<char>();
foreach (var element in str.ToCharArray())
{
if(nonDuplicates.Count == 0 || nonDuplicates.Last() != element)
nonDuplicates.Add(element);
}
var result = new string(nonDuplicates.ToArray());
Update
With reference to comment from , I have updated and the answer with two more solutions and ran the benchmark on them. The results are shown below.
Using String Append
var str = "aaaabbcccghbcccciippppkkllk";
var strResult = string.Empty;
foreach (var element in str.ToCharArray())
{
if (strResult.Length == 0 || strResult[strResult.Length - 1] != element)
strResult = $"{strResult}{element}";
}
Using StringBuilder
var str = "aaaabbcccghbcccciippppkkllk";
var strResult = new StringBuilder();
foreach (var element in str.ToCharArray())
{
if (strResult.Length == 0 || strResult[strResult.Length - 1] != element)
strResult.Append(element);
}
var result = strResult.ToString();
Benchmark Results
Method | Mean | Error | StdDev | Median |
------------------- |-----------:|----------:|-----------:|-----------:|
UsingList | 809.7 ns | 11.975 ns | 11.202 ns | 806.5 ns |
UsingStringAppend | 1,738.0 ns | 39.269 ns | 109.467 ns | 1,697.2 ns |
UsingStringBuilder | 201.6 ns | 1.960 ns | 1.834 ns | 201.1 ns |
As seen in the results, the StrinbBuilder Approach is much fast when compared to List. The string append approach is slowest.
Input
aaaabbcccghbcccciippppkkllk
Output
abcghbcipklk