Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on uppercase only if next character is lowercase

Tags:

string

c#

split

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?

like image 923
stoic Avatar asked Mar 18 '14 17:03

stoic


2 Answers

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

like image 90
Anthony Chu Avatar answered Oct 06 '22 00:10

Anthony Chu


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

like image 28
Brocco Avatar answered Oct 06 '22 00:10

Brocco