I can already sense the flames, but I like regex for this kind of stuff.
public static string UnCamelCase(string str)
{
return Regex.Replace(str, "([a-z])([A-Z])", "$1 $2");
}
(This may not be faster than your implementation, but to me it is more clear.)
And obviously, this would be even faster (at runtime)
private static Regex _unCamelRegex = new Regex("([a-z])([A-Z])", RegexOptions.Compiled);
public static string UnCamelCase(string str)
{
return _unCamelRegex.Replace(str, "$1 $2");
}
This would handle the issue brought up by Pete Kirkham below (as far as camel-cased strings like HTTPRequest):
private static Regex _unCamelRegex1 = new Regex("([a-z])([A-Z])", RegexOptions.Compiled);
private static Regex _unCamelRegex2 = new Regex("([A-Z]+)([A-Z])([a-z])", RegexOptions.Compiled);
public static string UnCamelCase(string str)
{
return _unCamelRegex2.Replace(_unCamelRegex1.Replace(str, "$1 $2"), "$1 $2$3");
}
This one takes HTTPRequestFOOBarGork
and returns HTTP Request FOO Bar Gork
So I tested the iterative method against the regular expression method using the OPs implementation (with the 'start at 1 and skip the > 0 check' change) and my second reply (the one with the static compiled Regex object). Note that the results do not include the compilation time of the Regex. For 2 million calls (using the same FooBarGork input):
Iterative: 00:00:00.80
Regex: 00:00:06.71
So it is quite obvious the that iterative approach is much more efficient. I've included a fixed version of the OPs implementation (as suggested by JPunyon, any credit should go to him) that also takes into account a null or empty argument:
public static string UnCamelCaseIterative(string str)
{
if (String.IsNullOrEmpty(str))
return str;
/* Note that the .ToString() is required, otherwise the char is implicitly
* converted to an integer and the wrong overloaded ctor is used */
StringBuilder sb = new StringBuilder(str[0].ToString());
for (int i = 1; i < str.Length; i++)
{
if (char.IsUpper(str, i))
sb.Append(" ");
sb.Append(str[i]);
}
return sb.ToString();
}