C# string.split() separate string by uppercase

Viewed 18698

I've been using the Split() method to split strings. But this work if you set some character for condition in string.Split(). Is there any way to split a string when is see Uppercase?

Is it possible to get few words from some not separated string like:

DeleteSensorFromTemplate

And the result string is to be like:

Delete Sensor From Template
5 Answers

Another way with regex:

public static string SplitCamelCase(string input)
{
   return System.Text.RegularExpressions.Regex.Replace(input, "([A-Z])", " $1", System.Text.RegularExpressions.RegexOptions.Compiled).Trim();
}

I had some fun with this one and came up with a function that splits by case, as well as groups together caps (it assumes title case for whatever follows) and digits.

Examples:

Input -> "TodayIUpdated32UPCCodes"

Output -> "Today I Updated 32 UPC Codes"

Code (please excuse the funky symbols I use)...

public string[] SplitByCase(this string s) {
   var ʀ = new List<string>();
   var ᴛ = new StringBuilder();
   var previous = SplitByCaseModes.None;
   foreach(var ɪ in s) {
      SplitByCaseModes mode_ɪ;
      if(string.IsNullOrWhiteSpace(ɪ.ToString())) {
         mode_ɪ = SplitByCaseModes.WhiteSpace;
      } else if("0123456789".Contains(ɪ)) {
         mode_ɪ = SplitByCaseModes.Digit;
      } else if(ɪ == ɪ.ToString().ToUpper()[0]) {
         mode_ɪ = SplitByCaseModes.UpperCase;
      } else {
         mode_ɪ = SplitByCaseModes.LowerCase;
      }
      if((previous == SplitByCaseModes.None) || (previous == mode_ɪ)) {
         ᴛ.Append(ɪ);
      } else if((previous == SplitByCaseModes.UpperCase) && (mode_ɪ == SplitByCaseModes.LowerCase)) {
         if(ᴛ.Length > 1) {
            ʀ.Add(ᴛ.ToString().Substring(0, ᴛ.Length - 1));
            ᴛ.Remove(0, ᴛ.Length - 1);
         }
         ᴛ.Append(ɪ);
      } else {
         ʀ.Add(ᴛ.ToString());
         ᴛ.Clear();
         ᴛ.Append(ɪ);
      }
      previous = mode_ɪ;
   }
   if(ᴛ.Length != 0) ʀ.Add(ᴛ.ToString());
   return ʀ.ToArray();
}

private enum SplitByCaseModes { None, WhiteSpace, Digit, UpperCase, LowerCase }

Here's another different way if you don't want to be using string builders or RegEx, which are totally acceptable answers. I just want to offer a different solution:

string Split(string input)
{
    string result = "";
    
    for (int i = 0; i < input.Length; i++)
    {
        if (char.IsUpper(input[i]))
        {
            result += ' ';
        }
    
        result += input[i];
    }
    
    return result.Trim();
}
Related