Last active
September 18, 2019 06:16
-
-
Save guitarrapc/5bf32bd1883acf4f6f20a8c7d86d1241 to your computer and use it in GitHub Desktop.
UpperCamel (Pascal) / smallCamel / smallcase to UPPER_SNAKE case.
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
void Main() | |
{ | |
ToUpperSnake("HogeMoge").Dump(); | |
ToUpperSnake("fugafuga").Dump(); | |
ToUpperSnake("hogeMoge").Dump(); | |
ToUpperSnake("PIYOPIYO").Dump(); | |
ToUpperSnake("PIYO_PIYO").Dump(); | |
ToUpperSnake("PIYO_PIYxO").Dump(); | |
ToUpperSnake("piyo_piyo").Dump(); | |
ToUpperSnake("piyo_piYo").Dump(); | |
} | |
public string ToUpperSnake(string text) | |
{ | |
if (text == text.ToUpper()) return text; | |
var builder = new StringBuilder(); | |
for (var i = 0; i < text.Length; i++) | |
{ | |
var c = text[i]; | |
if (char.IsUpper(c)) | |
{ | |
// initial letter don't need _ | |
if (i != 0 && char.IsLower(text[i - 1])) | |
{ | |
builder.Append('_'); | |
} | |
builder.Append(c); | |
continue; | |
} | |
else if (char.IsLower(c)) | |
{ | |
builder.Append(char.ToUpper(c, CultureInfo.InvariantCulture)); | |
} | |
else | |
{ | |
builder.Append(c); | |
} | |
} | |
var result = builder.ToString(); | |
return result; | |
} |
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
public class KotlinConverterTests | |
{ | |
[Theory] | |
[InlineData("HogeMoge", "HOGE_MOGE")] // PascalCase | |
[InlineData("hogeMoge", "HOGE_MOGE")] // smallCamel | |
[InlineData("PIYOPIYO", "PIYOPIYO")] // UPPERCASE | |
[InlineData("PIYO_PIYO", "PIYO_PIYO")] // UPPER_SNAKE | |
[InlineData("PIYO_PIYxO", "PIYO_PIYX_O")] // UPPERSNAKE + Pascal | |
[InlineData("piyopiyo", "PIYOPIYO")] // smallcase | |
[InlineData("piyo_piyo", "PIYO_PIYO")] // small_snake | |
[InlineData("piyo_piyXo", "PIYO_PIY_XO")] // smallsnake + smallCase | |
public void UpperSnakeConvert(string input, string expected) | |
{ | |
var actual = UpperSnake(input); | |
Assert.Equal(expected, actual); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
HOGE_MOGE
FUGAFUGA
HOGE_MOGE
PIYOPIYO
PIYO_PIYO
PIYO_PIYX_O
PIYO_PIYO
PIYO_PI_YO