在 C# 优化中使用 Replace 和 Substring 过滤字符串
Filtering string with Replace & Substring in C# Optimisation
我通过使用 .Replace 方法删除各种字符创建了一个 'filter' 字符串的函数,我还使用 Substring 方法删除了字符串末尾以“(”开头的任何内容。
一切正常,但是我想知道是否有更好的优化方法来执行此操作,因为效率对我来说很重要。
public static string filterHorseName(string horseName)
{
horseName = horseName
.Replace(" ", "")
.Replace("`", "")
.Replace("-", "")
.Replace("'", "")
.Replace("´", "")
.Replace("’", "")
.ToLower();
int index = horseName.IndexOf("(");
if (index > 0)
{
horseName = horseName.Substring(0, index);
}
return horseName;
}
谢谢。
我建议在 StringBuilder
:
的帮助下 构建 最后的 string
private static HashSet<char> charsToRemove = new HashSet<char>() {
' ', '`', '-', '\'', '´', '’'
};
public static string filterHorseName(string horseName) {
if (string.IsNullOrEmpty(horseName))
return horseName;
StringBuilder sb = new StringBuilder(horseName.Length);
foreach (char c in horseName) {
if (charsToRemove.Contains(c))
continue;
else if (c == '(')
break;
sb.Append(char.ToLower(c));
}
return sb.ToString();
}
我通过使用 .Replace 方法删除各种字符创建了一个 'filter' 字符串的函数,我还使用 Substring 方法删除了字符串末尾以“(”开头的任何内容。
一切正常,但是我想知道是否有更好的优化方法来执行此操作,因为效率对我来说很重要。
public static string filterHorseName(string horseName)
{
horseName = horseName
.Replace(" ", "")
.Replace("`", "")
.Replace("-", "")
.Replace("'", "")
.Replace("´", "")
.Replace("’", "")
.ToLower();
int index = horseName.IndexOf("(");
if (index > 0)
{
horseName = horseName.Substring(0, index);
}
return horseName;
}
谢谢。
我建议在 StringBuilder
:
string
private static HashSet<char> charsToRemove = new HashSet<char>() {
' ', '`', '-', '\'', '´', '’'
};
public static string filterHorseName(string horseName) {
if (string.IsNullOrEmpty(horseName))
return horseName;
StringBuilder sb = new StringBuilder(horseName.Length);
foreach (char c in horseName) {
if (charsToRemove.Contains(c))
continue;
else if (c == '(')
break;
sb.Append(char.ToLower(c));
}
return sb.ToString();
}