Chr*_*Kee 77 c# string refactoring immutability
有没有更好的方法来做到这一点......
MyString.Trim().Replace("&", "and").Replace(",", "").Replace(" ", " ")
.Replace(" ", "-").Replace("'", "").Replace("/", "").ToLower();
Run Code Online (Sandbox Code Playgroud)
我已经扩展了字符串类以使其保持一个工作但是有更快的方法吗?
public static class StringExtension
{
public static string clean(this string s)
{
return s.Replace("&", "and").Replace(",", "").Replace(" ", " ")
.Replace(" ", "-").Replace("'", "").Replace(".", "")
.Replace("eacute;", "é").ToLower();
}
}
Run Code Online (Sandbox Code Playgroud)
只是为了好玩(以及停止评论中的论点),我已经推动了以下各种示例的基准测试.
正则表达式选项得分非常高; 字典选项最快; stringbuilder replace的long winded版本比short hand稍快.
小智 106
更快 - 没有.更有效 - 是的,如果您将使用该StringBuilder
课程.在您的实现中,每个操作都会生成一个字符串的副本,在这种情况下可能会影响性 字符串是不可变对象,因此每个操作只返回修改后的副本.
如果您希望在多个Strings
重要长度上主动调用此方法,那么将其实现"迁移"到StringBuilder
类上可能会更好.有了它,任何修改都直接在该实例上执行,因此您可以节省不必要的复制操作.
public static class StringExtention
{
public static string clean(this string s)
{
StringBuilder sb = new StringBuilder (s);
sb.Replace("&", "and");
sb.Replace(",", "");
sb.Replace(" ", " ");
sb.Replace(" ", "-");
sb.Replace("'", "");
sb.Replace(".", "");
sb.Replace("eacute;", "é");
return sb.ToString().ToLower();
}
}
Run Code Online (Sandbox Code Playgroud)
Pao*_*sco 13
也许更具可读性?
public static class StringExtension {
private static Dictionary<string, string> _replacements = new Dictionary<string, string>();
static StringExtension() {
_replacements["&"] = "and";
_replacements[","] = "";
_replacements[" "] = " ";
// etc...
}
public static string clean(this string s) {
foreach (string to_replace in _replacements.Keys) {
s = s.Replace(to_replace, _replacements[to_replace]);
}
return s;
}
}
Run Code Online (Sandbox Code Playgroud)
还添加New In Town关于StringBuilder的建议......
The*_*iot 12
这将更有效:
public static class StringExtension
{
public static string clean(this string s)
{
return new StringBuilder(s)
.Replace("&", "and")
.Replace(",", "")
.Replace(" ", " ")
.Replace(" ", "-")
.Replace("'", "")
.Replace(".", "")
.Replace("eacute;", "é")
.ToString()
.ToLower();
}
}
Run Code Online (Sandbox Code Playgroud)
Tim*_*imS 11
如果你只是在一个漂亮的解决方案之后并且不需要节省几纳秒,那么一些LINQ糖怎么样?
var input = "test1test2test3";
var replacements = new Dictionary<string, string> { { "1", "*" }, { "2", "_" }, { "3", "&" } };
var output = replacements.Aggregate(input, (current, replacement) => current.Replace(replacement.Key, replacement.Value));
Run Code Online (Sandbox Code Playgroud)
在建议的解决方案中可能有一件事可以优化。进行多次调用Replace()
会使代码对同一字符串进行多次传递。对于很长的字符串,由于CPU缓存容量不足,解决方案可能会很慢。也许应该考虑一次更换多个字符串。