【问题标题】:How to save string index如何保存字符串索引
【发布时间】:2012-11-23 08:02:19
【问题描述】:
我有一个字符串,它的每个字符都存储在一个类似
的字符中
char currentLetter;
当循环运行 i=0 时,字符串的第一个字母被复制到 currentLetter。并在i=1 上复制第二个字母。
但是,我希望我保存特定字母的每个字符串索引。
我该怎么做?
【问题讨论】:
标签:
iphone
objective-c
xcode
nsstring
char
【解决方案1】:
NSString *str = @"Hello World";
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSUInteger i = 0; i < [str length]; i++)
{
if ([str characterAtIndex:i] == 'o')
[indexSet addIndex:i];
}
// indexSet now contains all the indexes of the letter 'o' in "str"
// which should be 4 and 7.
NSIndexSet 和 NSMutableIndexSet 类对于存储索引很有用,因为它们提供了其他方法来操作和有效处理索引。