Skip to content

Instantly share code, notes, and snippets.

@AntonC9018
Created June 27, 2022 17:19
Show Gist options
  • Save AntonC9018/fbc70225ec7dd348a580be25e7289942 to your computer and use it in GitHub Desktop.
Save AntonC9018/fbc70225ec7dd348a580be25e7289942 to your computer and use it in GitHub Desktop.
ToPascalCase
using System;
using System.Diagnostics;
using System.Text;
public class NotThreadSafeHelper
{
private static readonly StringBuilder _StringBuilderCached = new();
// Not thread safe! Reuses a static buffer.
public static string ToPascalCase(ReadOnlySpan<char> input)
{
ToPascalCase(input, _StringBuilderCached);
return _StringBuilderCached.ToString();
}
public static void ToPascalCase(ReadOnlySpan<char> input, StringBuilder output)
{
output.Clear();
int i = 0;
if (input.Length == 0)
return;
{
char ch = input[i];
i++;
if (ch >= 'a' && ch <= 'z')
output.Append((char)(ch + 'A' - 'a'));
else if (ch != ' ' && ch != '_' && ch != '-')
output.Append(ch);
}
while (i != input.Length)
{
char ch = input[i];
i++;
if (ch == ' ' || ch == '_' || ch == '-')
{
if (i == input.Length)
break;
ch = input[i];
if (ch >= 'a' && ch <= 'z')
{
output.Append((char)(ch + 'A' - 'a'));
i++;
}
}
else
{
output.Append(ch);
}
}
}
public static void Main()
{
Debug.Assert(ToPascalCase("abc") == "ABC");
Debug.Assert(ToPascalCase("camelCase") == "CamelCase");
Debug.Assert(ToPascalCase("aa-bb-cc") == "AaBbCc");
Debug.Assert(ToPascalCase("hello_world") == "HelloWorld");
Debug.Assert(ToPascalCase("123kf") == "123kf");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment