1

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

4

3 回答 3

3

开始遍历一个字符串并将每个字符与另一个字符串中相同索引处的字符进行比较。比较失败的地方是改变字符的索引。

于 2012-04-21T13:43:28.530 回答
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]);
于 2012-04-21T16:07:54.967 回答
1

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

于 2012-04-21T14:38:01.360 回答