DEV Community

Discussion on: Challenge of day #21 - Split a String in Balanced Strings

Collapse
uchitesting profile image
UchiTesting • Edited on

I did solve that problem my way with C#.

Here is the code:

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string s = "RLRRLLRLRL";
        Console.WriteLine($"Output: {BalancedString(s)}");
    }

    // Assuming there can be only 'L' and 'R' in the string
    static int BalancedString(string s) {
        CheckBalancedString(s);

        int count = 0;

        for(int i=0; i< s.Length - 1;i++){
            if (!s[i].Equals(s[i+1])) {
                count++;
                i++; // Next index is part of the set hence he hop it.
            }
        }

        return count;
    }

    static void CheckBalancedString(string s){
        Regex r = new Regex("^[LR]*$");
        if (!r.IsMatch(s)) throw new Exception("Sentence can only be made of 'L' and 'R' characters.");
        else Console.WriteLine($"{s} matches the expression.");

    }
}
Enter fullscreen mode Exit fullscreen mode

I put a link to that .NET Fiddle to play around.
Output Screenshot