Created
June 27, 2022 17:19
-
-
Save AntonC9018/fbc70225ec7dd348a580be25e7289942 to your computer and use it in GitHub Desktop.
ToPascalCase
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
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