读取 NSString 中的每个字符
是否可以在 Objective-C 框架内识别 NSString 中特定字符的位置和存在?例如,如果我有 NSString @"hello" 并且我想知道字符“e”的位置和存在,我该如何做到这一点?
Is it possible to identify the location and presence of a specific char in a NSString within the objective-c framework? For example, if I have the NSString @"hello" and I wanted to know the location and presence of the char "e", how would I be able to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一种特殊的方法可以在字符串中搜索单个字符,但您可以只搜索长度为 1 的子字符串的范围并请求返回的范围的位置,如下所示:
您可以在此处找到完整的文档:
rangeOfString:
查找所有
@"e"
的索引@"hello"
不过,您可能想做这样的事情:文档:NSMutableIndexSet,NSIndexSet
编辑: 将算法替换为@bbum 正如他对此答案的评论中所述。
There is particular method for searching for single characters within a string, but you can just search for the range of a substring of length 1 and request the returned range's location, as such:
You can find full documentation here:
rangeOfString:
To find the indices of all
@"e"
in@"hello"
you might want to do something like this, though:Documentation: NSMutableIndexSet, NSIndexSet
Edit: Replaced algorithm with the one from @bbum's as described in his comment to this answer.
查看 Apple 文档
Take a look at the Apple Docs for NSString.