Home
Manage Your Code
Snippet: Split a pascal-case string (C#)
Title: Split a pascal-case string Language: C#
Description: This little method (in C#) splits a pascal-cased string along the word boundaries to put spaces between the words. A pascal-cased string is a string where each word boundary begins with a capital letter. Views: 82
Author: Ben Ramey Date Added: 6/25/2010
Copy Code  
1    public static string SpacePascalCase(string input)
2    {
3      string splitString = String.Empty;
4
5      for (int idx = 0; idx < input.Length; idx++)
6      {
7        char c = input[idx];
8
9        if (Char.IsUpper(c)
10          // keeps abbreviations together like "Number HEI"

11          // instead of making it "Number H E I"

12            && ((idx < input.Length - 1
13                    && !Char.IsUpper(input[idx + 1]))
14                || (idx != 0
15                    && !Char.IsUpper(input[idx - 1])))
16            && splitString.Length > 0)
17        {
18          splitString += " ";
19        }
20
21        splitString += c;
22      }
23
24      return splitString;
25    }
Notes
This method attempts as best as it can to keep abbreviations together. So, something like NumberBOB would be spaced to Number BOB and not Number B O B.