如何访问 NSString 中的第 n 个字符?
我有十六进制颜色作为 NSStrings,并且想要检查特定字符串是否在第一个、第三个或第五个字符处包含 F,但如果它在第二个、第四个或第六个字符处包含 F,则忽略它。
这是为了确定所讨论的颜色是否是浅色。
我搜索了这个,但只找到了有关如何查找字符范围的答案。
I've got HEX colors as NSStrings and want to check if a particular string contains an F at the first, third, or fifth character, but to ignore it if it contains an F at the second, fourth or sixth character.
This is to identify if the color in question is a light color or not.
I searched for this, but only found answers regarding how to find character ranges.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 NSString 的 characterAtIndex 成员。
You can use the characterAtIndex member of NSString.
正如 @Daniel Pereira 所说,您可以使用
-[NSString characterAtIndex:]
方法来检查字符。As @Daniel Pereira says, you can use the
-[NSString characterAtIndex:]
method to check characters.您是否尝试过使用
characterAtIndex
?您可以使用该方法检索第一个、第三个和第五个字符处的字符串(当然一次一个)并将其与 F 进行比较。请注意,所有十六进制颜色都必须是 6 个字符。有时,您可以只用三个十六进制值表示颜色(例如,FFF 在 HTML 中仍会显示白色)。因此,如果您的颜色仅使用三个字符表示,并且您尝试获取索引 5 处的字符,则该方法将抛出“超出范围”异常。
Have you tried to use
characterAtIndex
? You can use the method to retrieve the string at the first, third and fifth character (of course one at a time) and compare it with F.Note that all your HEX colors must be 6 characters. Sometimes, you can represent a color with only three hex values (eg. FFF would still give you white in HTML). So if your color is represented using three chars only, and you try to get the char at index 5, the method will throw an 'out of range' exception.