对于字符串,查找并替换
在 C 字符串中查找一些文本并将其替换为新文本可能比预期的要棘手一些。 我正在寻找一种快速且时间复杂度小的算法。
我应该用什么?
Finding some text and replacing it with new text within a C string can be a little trickier than expected.
I am searching for an algorithm which is fast, and that has a small time complexity.
What should I use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我找不到我喜欢的 C 语言搜索/替换实现,所以我在这里展示我自己的实现。它不使用 strstr()、snprintf()、任意长度临时缓冲区等。它只要求 haystack 缓冲区足够大以容纳替换后的结果字符串。
使用示例
输出
干杯。
I couldn't find an implementation of search/replace in C that I liked so I present here my own. It does not use things like strstr(), snprintf(), arbitrary length temporary buffers, etc. It only requires that the haystack buffer is large enough to hold the resulting string after replacements are made.
Example usage
Output
Cheers.
Knuth-Morris-Pratt(经典)或 Boyer-Moore(有时更快)?
尝试使用 Google搜索“字符串搜索算法”。
Knuth-Morris-Pratt (which is classic) or Boyer-Moore (which is sometimes faster)?
Try using a Google search for 'string searching algorithms'.
我忍不住想知道 strstr() 实现了什么算法。鉴于这些是相当标准的算法,strstr() 的良好实现完全有可能使用其中之一。
但是,不能保证 strstr() 实现优化的算法,或者从一个平台到另一个平台使用相同的算法。
I can't help but wonder what algorithm strstr() implements. Given that these are fairly standard algorithms, it's entirely possible that a good implementation of strstr() uses one of them.
However there's no guarantee that strstr() implements an optimised algorithm or that the same algorithm is used from one platform to another.
使用
std::string
(来自
),您可以简单地使用find
和replace
。编辑:触摸。这仅适用于 C++。
这对你有好处吗?
http://www.daniweb.com/forums/thread51976.html
Using
std::string
(from<string>
) you can simply usefind
andreplace
.Edit: Touché. This is for C++ only.
Is this any good to you?
http://www.daniweb.com/forums/thread51976.html
这是一个很好的代码
here is a nice code
我的解决方案基于其他解决方案,但我认为更安全:
My solution, based on the others, but a bit safer I believe: