I have found numerous examples on how to split a string on uppercase, example:
"MyNameIsRob" returns "My Name Is Rob" 
My scenario is a bit differnet through....
I would like to accomplish the following:
"MyFavouriteChocIsDARKChocalate" should return "My Favourite Choc Is DARK Chocalate" 
The only way I can think of doing this, is to only split the string on upperacase if the next character is lowercase.
Any idea on how to achieve this?
You can do a Regex replace with lookahead and lookbehind to find uppercase with a lowercase before or after it...
var input = "MyFavouriteChocIsDARKChocalate";
var output = Regex.Replace(input, "(((?<!^)[A-Z](?=[a-z]))|((?<=[a-z])[A-Z]))", " $1");
Console.WriteLine(output);
http://dotnetfiddle.net/cIM6QG
Without regex, you could use this:
public static string SplitOnCaps(string s)
http://dotnetfiddle.net/qQIIgX :
using System;
using System.Collections.Generic;
using System.Text;
public class Program
{
    public static void Main()
    {
        /*"MyFavouriteChocIsDARKChocalate" should return "My Favourite Choc Is DARK Chocalate"*/
        var input = "MyFavouriteChocIsDARKChocalate";
        var split = SplitOnCaps(input);
        Console.WriteLine(input + " --> " + split);
        var match = "My Favourite Choc Is DARK Chocalate";
        Console.WriteLine(split == match ? "Match" : "No Match");       
    }
    public static string SplitOnCaps(string s)
    {
        var splits = new List<int>();
        var chars = s.ToCharArray();
        for(var i=1; i<chars.Length-1; i++)
        {
            if (IsCapital(chars[i]) && !IsCapital(chars[i+1]) ||
               IsCapital(chars[i]) && !IsCapital(chars[i-1]))
            {
                splits.Add(i);
            }
        }
        var sb = new StringBuilder();
        var lastSplit = 0;
        foreach(var split in splits)
        {
            sb.Append(s.Substring(lastSplit, split - lastSplit) + " ");
            lastSplit = split;
        }
        sb.Append(s.Substring(lastSplit));
        return sb.ToString();
    }
    public static bool IsCapital(char c)
    {
        var i = (int)c;
        return i>=65 && i<=90;
    }
}
Note: I am not fluent in Regex
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With