Created
June 18, 2014 08:38
-
-
Save umair-me/6f90d93c30f11fc5fdfd to your computer and use it in GitHub Desktop.
This method will return a string with spaces inserted before the capitals (excluding the first character).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// This method will return a string with spaces inserted before the capitals (excluding the first character). | |
/// So, "ThisIsAString" will become "This Is A String" (hopefully) | |
/// </summary> | |
/// <param name="s">The string that you want to be nicely formatted</param> | |
/// <returns></returns> | |
public static string InsertSpaceBeforeCapitals(string s) | |
{ | |
char[] tmpTitleArr = s.ToCharArray(); | |
bool nextCharCapitalise = false; | |
for (int i = 0; i < tmpTitleArr.Length; ++i) | |
{ | |
//if not the first character and there isn't space before hand, insert one. | |
if (i > 0 && | |
tmpTitleArr[i - 1] != ' ' && | |
Char.IsUpper(tmpTitleArr[i])) | |
{ | |
char[] newTitleArr = new char[tmpTitleArr.Length + 1]; | |
bool inserted = false; | |
for (int j = 0; j < tmpTitleArr.Length; ++j) | |
{ | |
if (j == i) | |
{ | |
newTitleArr[j] = ' '; | |
inserted = true; | |
} | |
newTitleArr[j + (inserted ? 1 : 0)] = tmpTitleArr[j]; | |
} | |
tmpTitleArr = newTitleArr; | |
} | |
//If this character is a space then we know the next character should be upper case. | |
if (tmpTitleArr[i] == ' ' || i == 0) | |
{ | |
nextCharCapitalise = true; | |
} | |
//Capitalise! | |
if (nextCharCapitalise && Char.IsLetter(tmpTitleArr[i])) | |
{ | |
tmpTitleArr[i] = Char.ToUpper(tmpTitleArr[i]); | |
nextCharCapitalise = false; | |
} | |
} | |
return new string(tmpTitleArr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment