Couldn't resist: The following is a rewrite of Alternative 9, ToggleCaseHA()
This is an unmanaged version which does direct manipulation of the input string
unsafe static string ToggleCaseUnmanaged(string str)
{
fixed(char* p = str)
{
for(int i=str.Length-1;i!=-1;--i)
{
char ch = p[i];
char foo = (char)(ch & ~0x20);
if((foo >= 0x41 && foo <= 0x5a) || (foo >= 0xc0 && foo<=0xde && foo != 0xd7))
{
p[i] = (char)(ch ^ 0x20);
}
else if((foo == 0xdf || ch>0xff) && char.IsLetter(ch))
{
p[i] = char.IsLower(ch) ? char.ToUpper(ch) : ch;
}
}
}
return str;
}
WARNING: This version will change the SOURCE string instead of creating a copy.
Using test phrase 4 available on
http://webinfocentral.com/resources/toggleCaseAlgorithm.aspx[
^] with 100.000 iterations:
ToggleCaseHA: 165,4507 milliseconds
ToggleCaseByCeChode: 117,3497 milliseconds
ToggleCaseUnmanaged: 67,367 milliseconds
----------------------------------------
Dear Michael,
Thanks for sharing this code snippet. There is minor bug in the code: when working w/Unicode string it does not toggle Lower to Upper (fixed in the following version, see Listing 1.).
Also, there is no need for return string as you already passed it as parameter ByRef and your code modifies it in that way that return value is the same as the value of the string passed as parameter. In production version the function could be void, but in this test version I've used return value for the duration in us.
In terms of performance: when tested on a standard ASCII your version appeared to be a speed champion in our "League of Best Toggle Case Algorithms" :) , but tested on Unicode string it demonstrated performance similar to the algorithm submitted by Henry Ayoola (you could refer to the test page and try the Unicode Test Phrase 2, for example, or enter your own).
Have a great day.
Kind regards,
Alex Bell
Listing 1. Class Library
using System;
namespace ToggleStringCase
{
public static class ToggleCase
{
unsafe public static string ToggleCaseUnmanagedByMBH(string str)
{
DateTime dt = DateTime.Now;
for (int j = 0; j < 100001; j++)
{
fixed (char* p = str)
{
for (int i = str.Length - 1; i != -1; --i)
{
char ch = p[i];
char foo = (char)(ch & ~0x20);
if ((foo >= 0x41 && foo <= 0x5a) ||
(foo >= 0xc0 && foo <= 0xde && foo != 0xd7))
{
p[i] = (char)(ch ^ 0x20);
}
else if ((foo == 0xdf || ch > 0xff) && char.IsLetter(ch))
{
p[i] = char.IsLower(ch) ? char.ToUpper(ch) : char.ToLower(ch);
}
}
}
}
TimeSpan ts = DateTime.Now - dt;
double dur = (double)ts.Milliseconds / 100;
return dur.ToString() + " us";
}
}
}
Listing 2: Calling Function (Button Click event)
protected void Button7_Click(object sender, EventArgs e)
{
string s = txtBox.Text;
Label7.Text = ToggleCase.ToggleCaseUnmanagedByMBH(s);
txtBox.Text = s;
}