Skip to content

Instantly share code, notes, and snippets.

@vanderlei-dev
Created July 22, 2020 02:23
Show Gist options
  • Save vanderlei-dev/b7410643327e83fcdce4ab855d9fcc40 to your computer and use it in GitHub Desktop.
Save vanderlei-dev/b7410643327e83fcdce4ab855d9fcc40 to your computer and use it in GitHub Desktop.
public ReadOnlySpan<char> FormatarCpf(string cpf)
{
Span<char> formattedValue = stackalloc char[14];
Copy(cpf, startIndex: 0, length: 3, ref formattedValue, insertIndex: 0);
formattedValue[3] = '.';
Copy(cpf, startIndex: 3, length: 3, ref formattedValue, insertIndex: 4);
formattedValue[7] = '.';
Copy(cpf, startIndex: 6, length: 3, ref formattedValue, insertIndex: 8);
formattedValue[11] = '-';
Copy(cpf, startIndex: 9, length: 2, ref formattedValue, insertIndex: 12);
return formattedValue.ToArray();
static void Copy(string origin, int startIndex, int length, ref Span<char> destination, int insertIndex)
{
for (int i = startIndex, j = insertIndex; i < (startIndex + length); i++, j++)
destination[j] = origin[i];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment