Skip to content

Instantly share code, notes, and snippets.

@guitarrapc
Last active September 18, 2019 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guitarrapc/5bf32bd1883acf4f6f20a8c7d86d1241 to your computer and use it in GitHub Desktop.
Save guitarrapc/5bf32bd1883acf4f6f20a8c7d86d1241 to your computer and use it in GitHub Desktop.
UpperCamel (Pascal) / smallCamel / smallcase to UPPER_SNAKE case.
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;
}
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);
}
}
@guitarrapc
Copy link
Author

HOGE_MOGE
FUGAFUGA
HOGE_MOGE
PIYOPIYO
PIYO_PIYO
PIYO_PIYX_O
PIYO_PIYO
PIYO_PI_YO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment