Created
July 19, 2014 08:55
-
-
Save chrisdavies/735daddd50510ed9d5b0 to your computer and use it in GitHub Desktop.
C# underscore string extension
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
// Convert a string to Underscore | |
public static class StringEx | |
{ | |
public static string Underscored(this string s) | |
{ | |
var builder = new StringBuilder(); | |
for (var i = 0; i < s.Length; ++i) | |
{ | |
if (ShouldUnderscore(i, s)) | |
{ | |
builder.Append('_'); | |
} | |
builder.Append(char.ToLowerInvariant(s[i])); | |
} | |
return builder.ToString(); | |
} | |
private static bool ShouldUnderscore(int i, string s) | |
{ | |
if (i == 0 || i >= s.Length || s[i] == '_') return false; | |
var curr = s[i]; | |
var prev = s[i - 1]; | |
var next = i < s.Length - 2 ? s[i + 1] : '_'; | |
return prev != '_' && ((char.IsUpper(curr) && (char.IsLower(prev) || char.IsLower(next))) || | |
(char.IsNumber(curr) && (!char.IsNumber(prev)))); | |
} | |
} | |
// Test it (requires Should) | |
namespace NadaissueWeb.Tests | |
{ | |
[TestClass] | |
public class UnderscoredTests | |
{ | |
[TestMethod] | |
public void UnderscoredOnCaps() | |
{ | |
"HelloWorldAndStuff".Underscored().ShouldEqual("hello_world_and_stuff"); | |
} | |
[TestMethod] | |
public void UnderscoredOnOnlyFirstAndLastCapInRun() | |
{ | |
"HelloABCStore".Underscored().ShouldEqual("hello_abc_store"); | |
} | |
[TestMethod] | |
public void UnderscoredHandlesEndingCaps() | |
{ | |
"HelloABC".Underscored().ShouldEqual("hello_abc"); | |
} | |
[TestMethod] | |
public void UnderscoredHandlesEndingNums() | |
{ | |
"Hello123".Underscored().ShouldEqual("hello_123"); | |
} | |
[TestMethod] | |
public void UnderscoredOnNumberRun() | |
{ | |
"Hello73Books".Underscored().ShouldEqual("hello_73_books"); | |
} | |
[TestMethod] | |
public void UnderscoredCamelCase() | |
{ | |
"helloWorld".Underscored().ShouldEqual("hello_world"); | |
} | |
[TestMethod] | |
public void UnderscoredLastCap() | |
{ | |
"HelloW".Underscored().ShouldEqual("hello_w"); | |
} | |
[TestMethod] | |
public void UnderscoredLastNum() | |
{ | |
"Hello1".Underscored().ShouldEqual("hello_1"); | |
} | |
[TestMethod] | |
public void UnderscoredExistingUnderscores() | |
{ | |
"hello_World".Underscored().ShouldEqual("hello_world"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment