Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class StringExtensions
- {
- private const char kSlugSeparatorChar = '-';
- public static string Slugify(this string str)
- {
- if (string.IsNullOrWhiteSpace(str))
- return string.Empty;
- // https://referencesource.microsoft.com/#mscorlib/system/text/stringbuildercache.cs
- var sb = StringBuilderCache.Acquire(str.Length * 2);
- foreach (var chr in str)
- {
- AddToCharBuffer(chr, ref sb);
- }
- // Create the resulting string and clear the character array buffer
- if (sb.Length > 0 && sb[^1] == kSlugSeparatorChar)
- sb.Length -= 1;
- // Done
- var result = StringBuilderCache.GetStringAndRelease(sb);
- return result;
- }
- private static void AddToCharBuffer(in char chr, ref StringBuilder builder)
- {
- if (chr == 0x00)
- return;
- // Determine whether the character represents a lowercase letter or a digit character
- if (chr >= 97 && chr <= 122 || char.IsDigit(chr))
- {
- // Lowercase letters or digits
- builder.Append(chr);
- return;
- }
- // Determine whether the character represents an uppercase letter
- if (chr >= 65 && chr <= 90)
- {
- // Uppercase letters
- builder.Append(char.ToLowerInvariant(chr));
- return;
- }
- // Only append separator if another character has already been added and
- // prevent adding two or more separators in a row
- if (builder.Length == 0 || builder[^1] == kSlugSeparatorChar)
- return;
- builder.Append(kSlugSeparatorChar);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement