例如:
thisIsMySample
应该:
this_Is_My_Sample
我的代码:
System.Text.RegularExpressions.Regex.Replace(input,"([A-Z])","_$0",System.Text.RegularExpressions.RegexOptions.Compiled);
它工作正常,但如果输入更改为:
ThisIsMySample
输出将为:
_This_Is_My_Sample
如何忽略第一次发生?
解决方法
非正则表达式解决方案
string result = string.Concat(input.Select((x,i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString()));
似乎也很快:正则表达式:2569ms,C#:1489ms
Stopwatch stp = new Stopwatch(); stp.Start(); for (int i = 0; i < 1000000; i++) { string input = "ThisIsMySample"; string result = System.Text.RegularExpressions.Regex.Replace(input,"(?<=.)([A-Z])",System.Text.RegularExpressions.RegexOptions.Compiled); } stp.Stop(); MessageBox.Show(stp.ElapsedMilliseconds.ToString()); // Result 2569ms Stopwatch stp2 = new Stopwatch(); stp2.Start(); for (int i = 0; i < 1000000; i++) { string input = "ThisIsMySample"; string result = string.Concat(input.Select((x,j) => j > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())); } stp2.Stop(); MessageBox.Show(stp2.ElapsedMilliseconds.ToString()); // Result: 1489ms
原文地址:https://www.jb51.cc/csharp/95756.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。