Split a character string based on change of character: Difference between revisions

Content added Content deleted
m (→‎{{header|Perl 6}}: Grammar tweaks, add commas to multi-byte character names for readability, update works-with)
(Added C# implementation)
Line 204: Line 204:
{{out}}
{{out}}
<pre>g, HHH, 5, YY, ++, ///, \</pre>
<pre>g, HHH, 5, YY, ++, ///, \</pre>

=={{header|C sharp}}==
<lang csharp>using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
string s = @"gHHH5YY++///\";
Console.WriteLine(s.RunLengthSplit().Delimit(", "));
}

public static class Extensions
{
public static IEnumerable<string> RunLengthSplit(this string source) {
using (var enumerator = source.GetEnumerator()) {
if (!enumerator.MoveNext()) yield break;
char previous = enumerator.Current;
int count = 1;
while (enumerator.MoveNext()) {
if (previous == enumerator.Current) {
count++;
} else {
yield return new string(Enumerable.Repeat(previous, count).ToArray());
previous = enumerator.Current;
count = 1;
}
}
yield return new string(Enumerable.Repeat(previous, count).ToArray());
}
}

public static string Delimit<T>(this IEnumerable<T> source, string separator = "") => string.Join(separator ?? "", source);
}</lang>
{{out}}
<pre>
g, HHH, 5, YY, ++, ///, \
</pre>


=={{header|C++}}==
=={{header|C++}}==
Line 234: Line 272:
{{out}}
{{out}}
<pre>g, HHH, 5, , )), YY, ++, ,,,, ///, \</pre>
<pre>g, HHH, 5, , )), YY, ++, ,,,, ///, \</pre>




=={{header|Clojure}}==
=={{header|Clojure}}==