21

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
evelikov92
  • 697
  • 3
  • 8
  • 28

5 Answers5

36

Use Regex.split

string[] split =  Regex.Split(str, @"(?<!^)(?=[A-Z])");
Bakudan
  • 18,466
  • 9
  • 50
  • 71
Avinash Raj
  • 166,785
  • 24
  • 204
  • 249
11

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();
}
Artem Bakhmat
  • 147
  • 1
  • 9
  • Don't know why this hasn't got more upvotes - great use of Trim to handle first and last upper case letters in a very readable, easy to understand bit of code. – GrayedFox Jan 08 '21 at 20:07
  • 1
    I extended it a bit to deal with acronyms (that could end in lower s), https://dotnetfiddle.net/VBuoy7 see console output for example cases – Frank Schwieterman Jul 03 '21 at 06:30
8

If you do not like RegEx and you really just want to insert the missing spaces, this will do the job too:

public static string InsertSpaceBeforeUpperCase(this string str)
{   
    var sb = new StringBuilder();

    char previousChar = char.MinValue; // Unicode '\0'

    foreach (char c in str)
    {
        if (char.IsUpper(c))
        {
            // If not the first character and previous character is not a space, insert a space before uppercase

            if (sb.Length != 0 && previousChar != ' ')
            {
                sb.Append(' ');
            }           
        }

        sb.Append(c);

        previousChar = c;
    }

    return sb.ToString();
}
gb2d
  • 6,390
  • 9
  • 57
  • 98
ChriPf
  • 2,612
  • 1
  • 22
  • 25
2

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 }
dynamichael
  • 689
  • 8
  • 8
0

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();
}
InvAdrian
  • 23
  • 1
  • 5