Skip to content

Instantly share code, notes, and snippets.

@sebgod
Last active August 29, 2015 14:03
Show Gist options
  • Save sebgod/546440ec8fc7acb23ce2 to your computer and use it in GitHub Desktop.
Save sebgod/546440ec8fc7acb23ce2 to your computer and use it in GitHub Desktop.
A astral character safe first char method for C#
static class FirstCharUtf32 {
public static bool FirstChar(string Str, out int First) {
bool SUCCESS_INDICATOR;
int len = Str.Length;
if (len > 0) {
First = Str[0];
if (char.IsSurrogate((char)First)) {
if (SUCCESS_INDICATOR = char.IsSurrogatePair(Str, 0)) {
First = char.ConvertToUtf32((char)First, Str[1]);
}
} else {
SUCCESS_INDICATOR = true;
}
} else {
First = 0;
SUCCESS_INDICATOR = false;
}
return SUCCESS_INDICATOR;
}
public static void TestFirstChar(char[] chars) {
int first;
string s = new string(chars);
bool success = FirstChar(s, out first);
string hex = ConvertStringToHex(s);
System.Console.WriteLine("First Char of {0} is {1:x} \t= {2}", hex, first, success);
}
public static void Main(string[] args) {
char c1 = (char)0xd800;
char c2 = (char)0xdc00;
TestFirstChar(new char[] {c1, c2});
TestFirstChar(new char[] {c1});
TestFirstChar(new char[] {c2});
TestFirstChar(new char[] {});
TestFirstChar(new char[] {'a'});
}
public static string ConvertStringToHex(string str)
{
System.Text.StringBuilder hex = new System.Text.StringBuilder(str.Length * 6 + 2);
hex.Append('"');
foreach (int codeUnit in str) {
hex.AppendFormat("\\u{0:X2}", codeUnit);
}
hex.Append('"');
return hex.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment