public static StringBuilder Reverse(this StringBuilder text)
{
int textLength = text.Length;
if (textLength > 1)
{
// Pull the string out of the StringBuilder so we
// can work with the various text elements (chars, glyphs, graphemes, etc)
// and reverse the order of the string without reversing chars that need to be
// in a specific order to represent the same text as the forward string.
// Reference: http://stackoverflow.com/a/36310993/181087
int offset = textLength;
var enumerator = StringInfo.GetTextElementEnumerator(text.ToString());
while (enumerator.MoveNext())
{
string element = enumerator.GetTextElement();
// Back up the current offset by the length of the element
offset -= element.Length;
for (int i = 0; i < element.Length; i++)
{
// Write the chars in forward order from the element
// to the StringBuilder based on the offset.
text[i + offset] = element[i];
}
}
}
return text;
}