仅替换 NSString 中子字符串的第一个实例
因此,如果您有一个 NSString:
@"My blue car is bigger than my blue shoes or my blue bicycle";
我想要一种仅用绿色替换蓝色的第一个实例的方法,以产生:
@"My green car is bigger than my blue shoes or my blue bicycle";
如何做到这一点?
So if you have an NSString that goes:
@"My blue car is bigger than my blue shoes or my blue bicycle";
I would like a method that replaces only the first instance of blue with green, to produce:
@"My green car is bigger than my blue shoes or my blue bicycle";
How does one do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
假设有以下输入:
该算法非常简单:
Assuming the following inputs:
The algorithm is quite simple:
SWIFT 3 和 4 更新:
SWIFT 3 and 4 UPDATE:
此处发布了更 Swift 版本的实现。这与 Swift 5.1 中语法
replacingOccurrences(of:with:)
的用法示例相同:
A more Swift'y version of the implementations posted here. This one matches the syntax
replacingOccurrences(of:with:)
in Swift 5.1An example of usage:
斯威夫特 4 版本:
Swift 4 version:
在 Swift 中,以这种方式扩展String很有用:
这样你就可以在任何地方调用:
In Swift is useful extends String in this way:
In this way you can call wherever:
首先找到子串,然后进行替换。示例:
NSString 文档。
First locate the substring, and then make the replacement. Example :
NSString documentation.