NSString中字符的索引

时间:2012-04-21 13:39:55

标签: iphone objective-c nsstring

我有NSString *string = @"Helo";NSString *editedString = @"Hello";。如何查找已更改字符或字符的索引(例如此处为@"l")。

3 个答案:

答案 0 :(得分:3)

开始浏览一个字符串,并将每个字符与另一个字符串中相同索引处的字符进行比较。比较失败的地方是更改后的字符的索引。

答案 1 :(得分:2)

我在NSString上写了一个类别,可以做你想做的事。我已经使用我的StackOverflow用户名作为类别方法的后缀。这是为了阻止一个不太可能的未来与同名方法的碰撞。随意改变它。

首先是界面定义NSString+Difference.h

#import <Foundation/Foundation.h>

@interface NSString (Difference)

- (NSInteger)indexOfFirstDifferenceWithString_mttrb:(NSString *)string;

@end

和实现'NSString + Difference.m`:

#import "NSString+Difference.h"

@implementation NSString (Difference)

- (NSInteger)indexOfFirstDifferenceWithString_mttrb:(NSString *)string; {

    // Quickly check the strings aren't identical
    if ([self isEqualToString:string]) 
        return -1;

    // If we access the characterAtIndex off the end of a string
    // we'll generate an NSRangeException so we only want to iterate
    // over the length of the shortest string
    NSUInteger length = MIN([self length], [string length]);

    // Iterate over the characters, starting with the first
    // and return the index of the first occurence that is 
    // different
    for(NSUInteger idx = 0; idx < length; idx++) {
        if ([self characterAtIndex:idx] != [string characterAtIndex:idx]) {
            return idx;
        }
    }

    // We've got here so the beginning of the longer string matches
    // the short string but the longer string will differ at the next
    // character.  We already know the strings aren't identical as we
    // tested for equality above.  Therefore, the difference is at the
    // length of the shorter string.

    return length;        
}

@end

您将使用以上内容:

NSString *stringOne = @"Helo";
NSString *stringTwo = @"Hello";

NSLog(@"%ld", [stringOne indexOfFirstDifferenceWithString_mttrb:stringTwo]);

答案 2 :(得分:1)

您可以使用-rangeOfString:。例如,[string rangeOfString:@"l"].location。该方法也有几种变体。