删除字符串的最佳方法是什么?
我需要具有最佳性能的想法来删除/过滤字符串
我有:
string Input = "view('512', 3, 159);";
删除“view(”和“)的最佳性能方法是什么;” 和报价? 我可以做这个:
Input = Input.Replace("view(","").Replace("'","").Replace("\"","").Replace(");","");
但它似乎相当不优雅。
Input.Split('(')[1].Split(')')[0].Replace("'", "");
看起来好多了
我希望不使用正则表达式; 我需要尽可能快地完成应用程序。 提前致谢! 🙂
您可以使用简单的linq语句:
string Input = "view('512', 3, 159);"; string output = new String( Input.Where( c => Char.IsDigit( c ) || c == ',' ).ToArray() );
输出:512,3,159
如果你想要空格,只需在where子句中添加一个检查。
您可以只使用一个Substring
来删除view(
和);
:
Input.Substring(5, Input.Length - 7)
除此之外,它看起来相当有效。 普通的字符串操作非常优化。
所以:
Input = Input.Substring(5, Input.Length - 7) .Replace("'", String.Empty) .Replace("\"", String.Enmpty);
char[] Output = Input.SkipWhile(x => x != '(') // skip before open paren .Skip(1) // skip open paren .TakeWhile(x => x != ')') // take everything until close paren .Where(x => x != '\'' && x != '\"') // except quotes .ToArray(); return new String(Output);
希望这可以帮助
Regex.Replace("view('512', 3, 159);",@"[(view)';]","")
IndexOf,LastIndexOf和Substring可能是最快的。
string Input = "view('512', 3, 159);"; int p1 = Input.IndexOf('('); int p2 = Input.LastIndexOf(')'); Input = Input.Substring (p1 + 1, p2 - p1 - 1);
使用以下内容:
System.Text.StringBuilder sb=new System.Text.StringBuilder(); int state=0; for(var i=0;i
var result = new string(Input.ToCharArray(). SkipWhile (i => i != '\''). TakeWhile (i => i != ')').ToArray());
你为什么不想使用正则表达式? 正则表达式经过了大量优化,并且比任何手写黑客都要快得多。
这是java(因为我运行linux并且无法运行c#),但我希望你能得到这个想法。
input.replace("view(","").replace("'","").replace("\"","").replace(");","");
在我的计算机上大约6秒内重复上述一百万次。 然而,下面的正则表达式在大约2秒内运行。
// create java's regex matcher object // matcher is looking for sequences of digits (valid integers) Matcher matcher = Pattern.compile("(\\d+)").matcher(s); StringBuilder builder = new StringBuilder(); // whilst we can find matches append the match plus a comma to a string builder while (matcher.find()) { builder.append(matcher.group()).append(','); } // return the built string less the last trailing comma return builder.substring(0, builder.length()-1);
如果要查找有效小数和整数,请改用以下模式。 虽然它比原来运行稍慢。
"(\\d+(\\.\\d*)?)"
更通用
void Main() { string Input = "view('512', 3, 159);"; var statingPoint = Input.IndexOf('(') + 1; var result = Input.Substring(statingPoint, Input.IndexOf(')') - statingPoint); }
最快的方法是Input = Input.Substring(5, Input.Length - 7)