给定字符串“ThisStringHasNoSpacesButItDoesHaveCapitals”,在大写字母前添加空格的最佳方法是什么。所以结束字符串将是“这个字符串没有空格但它有大写字母”
这是我对 RegEx 的尝试
System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " $0")
最佳答案
正则表达式可以很好地工作(我什至投票赞成 Martin Browns 的回答),但它们很昂贵(而且我个人认为任何超过几个字符的模式都非常迟钝)
这个函数
string AddSpacesToSentence(string text, bool preserveAcronyms)
{
if (string.IsNullOrWhiteSpace(text))
return string.Empty;
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]))
if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||
(preserveAcronyms && char.IsUpper(text[i - 1]) &&
i < text.Length - 1 && !char.IsUpper(text[i + 1])))
newText.Append(' ');
newText.Append(text[i]);
}
return newText.ToString();
}
将在 2,968,750 次滴答中执行 100,000 次,正则表达式将花费 25,000,000 次滴答(这是编译的正则表达式)。
它更好,对于更好(即更快)的给定值,但是需要维护的代码更多。 “更好”通常是对竞争要求的妥协。
希望这有帮助:)
更新
我已经很久没看这个了,我才意识到自从代码更改后时间还没有更新(它只更改了一点)。
在“Abbbbbbbbb”重复 100 次(即 1,000 字节)的字符串上,运行 100,000 次转换需要手动编码函数 4,517,177 个滴答,下面的正则表达式需要 59,435,719,使得手动编码函数运行时间占 7.6%它需要正则表达式。
更新 2 它会考虑首字母缩略词吗?现在会了! if 语句的逻辑相当模糊,如您所见,将其扩展为...
if (char.IsUpper(text[i]))
if (char.IsUpper(text[i - 1]))
if (preserveAcronyms && i < text.Length - 1 && !char.IsUpper(text[i + 1]))
newText.Append(' ');
else ;
else if (text[i - 1] != ' ')
newText.Append(' ');
...根本没有帮助!
这是不用担心首字母缩略词的原始简单方法
string AddSpacesToSentence(string text)
{
if (string.IsNullOrWhiteSpace(text))
return "";
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]) && text[i - 1] != ' ')
newText.Append(' ');
newText.Append(text[i]);
}
return newText.ToString();
}
关于c# - 在大写字母前加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/272633/