Igor Bidiniuc
Igor Bidiniuc

Reputation: 1560

Index for character in NSString

I have NSString *string = @"Helo"; and NSString *editedString = @"Hello";. How find index for changed character or characters (for example here is @"l").

Upvotes: 1

Views: 1135

Answers (3)

mttrb
mttrb

Reputation: 8345

I've written a category on NSString that will do what you want. I've used my StackOverflow username as a postfix on the category method. This is to stop an unlikely potential future collision with a method of the same name. Feel free to change it.

First the interface definition NSString+Difference.h:

#import <Foundation/Foundation.h>

@interface NSString (Difference)

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

@end

and the implementation '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

You would use the above as follows:

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

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

Upvotes: 2

Ken Thomases
Ken Thomases

Reputation: 90681

You can use -rangeOfString:. For example, [string rangeOfString:@"l"].location. There are several variants of that method, too.

Upvotes: 1

Alexander
Alexander

Reputation: 8147

Start going through one string and compare each character with the character at the same index in the other string. The place where the comparison fails is the index of the changed character.

Upvotes: 3

Related Questions