1

私は持っNSString *string = @"Helo";ていNSString *editedString = @"Hello";ます。変更された1つまたは複数の文字のインデックスを見つける方法(たとえば、ここにあります@"l")。

4

3 に答える 3

3

1つの文字列を調べ始め、各文字を他の文字列の同じインデックスにある文字と比較します。比較に失敗する場所は、変更された文字のインデックスです。

于 2012-04-21T13:43:28.530 に答える
2

私はあなたが望むことをするNSStringのカテゴリーを書きました。StackOverflowユーザー名をcategoryメソッドのpostfixとして使用しました。これは、同じ名前のメソッドとの起こりそうもない将来の衝突を防ぐためです。お気軽に変更してください。

最初にインターフェース定義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 に答える