Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Formatting / Splitting string from Title Case to Delimited Words
namespace tests
{
[TestClass]
public class string_extension_tests
{
[TestMethod]
public void when_formatting_title_case_to_delimited_but_the_delimiter_is_not_specified()
{
var s = "ThisIsTheDayThatTheLordHasMade";
var formated = s.TitleCaseToDelimited();
const string expected = "This Is The Day That The Lord Has Made";
Assert.AreEqual(expected, formated);
}
[TestMethod]
public void when_formatting_title_case_to_delimited_and_the_delimiter_is_specified()
{
var s = "ThisIsTheDayThatTheLordHasMade";
var formated = s.TitleCaseToDelimited("_");
const string expected = "This_Is_The_Day_That_The_Lord_Has_Made";
Assert.AreEqual(expected, formated);
}
}
/// <summary>
/// String helpers
/// </summary>
public static class StringExtensions
{
/// <summary>
/// It converts a string with the format of "ThisIsTheDayThatTheLordHasMade" to "This Is The Day The Lord Has Made"
/// insprired by the conversation here: http://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array
/// Limitation: this will split all upper cased letters into separate words. I don't have a need to for it now so go YAGNI
/// </summary>
/// <param name="str"></param>
/// <param name="delimiter"></param>
/// <returns></returns>
public static string TitleCaseToDelimited(this string str, params string[] delimiters)
{
//if there is no data, let's waste our breath
if (string.IsNullOrWhiteSpace(str)) return str;
//if not delimiter specified, use space
string delimiter;
if (delimiters.Length == 0 || string.IsNullOrWhiteSpace(delimiters[0])) delimiter = " ";
else delimiter = delimiters[0];
//regex does the magic
return Regex.Replace(str, "(\\B[A-Z])", delimiter + "$1");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.