23

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
  • 755
  • 3
  • 8
  • 30

5 Answers5

43

Use Regex.split

string[] split =  Regex.Split(str, @"(?<!^)(?=[A-Z])");
Bakudan
  • 19,134
  • 9
  • 53
  • 73
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
15

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
  • 187
  • 2
  • 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();
}
gbro3n
  • 6,729
  • 9
  • 59
  • 100
ChriPf
  • 2,700
  • 1
  • 23
  • 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
  • 807
  • 9
  • 9
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
  • 33
  • 1
  • 7
  • Actually this is helpful if you're trying to add extra things between like converting `HelloWorldThisIsAPhrase` to `Hello - World, this is a phrase` or something like that. :) Thanks! – Asfo Jun 17 '22 at 17:03
  • You’re most welcome! Glad it helps you in some way. – InvAdrian Jun 22 '22 at 21:13