我已经能感觉到火焰了,但我喜欢用正则表达式来处理这类东西。
public static string UnCamelCase(string str)
{
return Regex.Replace(str, "([a-z])([A-Z])", "$1 $2");
}
(这可能不会比您的实现更快,但是me更清楚了。)
显然,这会更快(在运行时)
private static Regex _unCamelRegex = new Regex("([a-z])([A-Z])", RegexOptions.Compiled);
public static string UnCamelCase(string str)
{
return _unCamelRegex.Replace(str, "$1 $2");
}
这将解决 Pete Kirkham 提出的问题below(就像 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");
}
这个需要HTTPRequestFOOBarGork
并返回HTTP Request FOO Bar Gork
因此,我使用 OP 实现(使用“从 1 开始并跳过 > 0 检查”更改)和我的第二个回复(带有静态编译的 Regex 对象的回复)针对正则表达式方法测试了迭代方法。请注意,结果不包括正则表达式的编译时间。对于 200 万次调用(使用相同的 FooBarGork 输入):
迭代:00:00:00.80
Regex:00:00:06.71
所以很明显迭代方法是much更高效。我已经包含了 OP 实现的固定版本(按照建议由 Jason Punyon 撰写,任何功劳都应归功于他),其中还考虑了 null 或空参数:
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();
}