SHARE
TWEET

Untitled

a guest Jan 24th, 2020 68 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class StringExtensions
  2. {
  3.  
  4.         private const char kSlugSeparatorChar = '-';
  5.  
  6.         public static string Slugify(this string str)
  7.         {
  8.             if (string.IsNullOrWhiteSpace(str))
  9.                 return string.Empty;
  10.  
  11.             // https://referencesource.microsoft.com/#mscorlib/system/text/stringbuildercache.cs
  12.             var sb = StringBuilderCache.Acquire(str.Length * 2);
  13.             foreach (var chr in str)
  14.             {
  15.                 AddToCharBuffer(chr, ref sb);
  16.             }
  17.  
  18.             // Create the resulting string and clear the character array buffer
  19.             if (sb.Length > 0 && sb[^1] == kSlugSeparatorChar)
  20.                 sb.Length -= 1;
  21.  
  22.             // Done
  23.             var result = StringBuilderCache.GetStringAndRelease(sb);
  24.             return result;
  25.         }
  26.  
  27.         private static void AddToCharBuffer(in char chr, ref StringBuilder builder)
  28.         {
  29.             if (chr == 0x00)
  30.                 return;
  31.  
  32.             // Determine whether the character represents a lowercase letter or a digit character
  33.             if (chr >= 97 && chr <= 122 || char.IsDigit(chr))
  34.             {
  35.                 // Lowercase letters or digits
  36.                 builder.Append(chr);
  37.                 return;
  38.             }
  39.  
  40.             // Determine whether the character represents an uppercase letter
  41.             if (chr >= 65 && chr <= 90)
  42.             {
  43.                 // Uppercase letters
  44.                 builder.Append(char.ToLowerInvariant(chr));
  45.                 return;
  46.             }
  47.  
  48.             // Only append separator if another character has already been added and
  49.             // prevent adding two or more separators in a row
  50.             if (builder.Length == 0 || builder[^1] == kSlugSeparatorChar)
  51.                 return;
  52.  
  53.             builder.Append(kSlugSeparatorChar);
  54.         }
  55. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top