Click here to Skip to main content
15,887,135 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

How to Toggle String Case in .NET

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
23 Mar 2011CPOL 5.1K   1  
And yet another ...5% slower ... than the fastest to date -> SimmoTech's v2,(an awesome piece of righteously parsimonious code).85% less filling ... the diet version -> 44 vs 256 bytes(.Net v2 and above)private const int AddressBitsPerUnit = 5;private const int BitsPerElement =...
And yet another ...

5% slower ... than the fastest to date -> SimmoTech's v2,
(an awesome piece of righteously parsimonious code).

85% less filling ... the diet version -> 44 vs 256 bytes

(.Net v2 and above)
C#
private const int AddressBitsPerUnit = 5;
private const int BitsPerElement = 32;
private const int BitIndexMask = BitsPerElement - 1;
private static readonly int[] ValidLatinChars = { 0, 0, 134217726, 134217726, 0, 0, 2139095039, 2139095039 };
public static string ToggleCase_SimmoTech_MacMaverick( string s )
{
  TextInfo currentCultureTextInfo = CultureInfo.CurrentCulture.TextInfo;
  char[] chs = s.ToCharArray();
  for ( int i = 0; i < s.Length; ++i )
  {
    char ch = chs[i];
    if ( ch <= 0xFF )
    {
      int bitSet = 1 << ( ch & BitIndexMask );
      if ( ( ValidLatinChars[( ch >> AddressBitsPerUnit )] & bitSet ) == bitSet )
      {
        chs[i] = (char) ( ch ^ 0x20 );
      }
      continue;
    }
    switch ( char.GetUnicodeCategory( ch ) )
    {
      case UnicodeCategory.UppercaseLetter:
        chs[i] = currentCultureTextInfo.ToLower( ch );
        break;
      case UnicodeCategory.LowercaseLetter:
        chs[i] = currentCultureTextInfo.ToUpper( ch );
        break;
    }
  }
  return ( new string( chs ) );
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --