字符串/子字符串查找和替换 [英] String/Substring find and replace

查看:180
本文介绍了字符串/子字符串查找和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用RegEx和C#搜索字符串并替换所有非数字字符...

字符串strung = Regex.Replace(unstrung,@"[^ \ w]","Strings");

我想知道的是:这是执行此简单操作的最快方法吗?我已经看到它引用了RegEx可能很慢,这似乎很简单.

奇怪的是,我对RegEx有很好的了解,但没有一种广泛的.Net字符串工具等...

I am currently using RegEx and C# to search a string and replace all non-numeric characters...

string strung = Regex.Replace(unstrung, @"[^\w]", "Strings");

What I am wondering is: Is this the fastest way to do this simple action? I have seen it quoted that RegEx can be slow and this seems a pretty simple thing.

Oddly I have a pretty ok knowledge of RegEx, but not one of the expansive .Net string tools etc...

Any help or direction pointing would be greatly appreciated.

推荐答案

这取决于您的选择.如果您的任务确实需要这样的替换,则您可能希望自己使用字符串操作来做等效的代码.很有可能它会比Regex慢.你好奇吗?

另外,如果您关心性能,它会告诉我您需要多次重复此操作(否则,谁会关心您的性能).在这种情况下,如果使用Regex构造函数而不是显示的静态方法,则可能会提高性能.这样就可以预解析正则表达式-只需一次.
It depend on your alternative. If your task really needs replacements like this, you may want to do equivalent code using string operations yourself. Good chances are it will be slower than Regex. Are you curious enough to try?

Also, if you care about performance, it tells me you need to repeat this operation many times (otherwise, who cares about your performance). In this case you may gain performance if you use Regex constructor, not the static method you show. In this way regular expression can be pre-parsed -- just once.


这肯定是最快的正则表达式.

如果您想尝试更快的方法,请成为一名程序员,然后尝试其他解决问题的方法.

此类任务的性能在很大程度上取决于所涉及字符串的长度.
It''s certainly the fastest way to type it.

If you want to try to find faster ways, be a programmer and try different ways to approach the problem.

Performance for such a task would greatly depend on the length of the string involved.


这篇关于字符串/子字符串查找和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆