2012-04-21 7 views

答えて

2

私は、あなたが望むことをするNSStringにカテゴリを書いています。私は、カテゴリメソッドのPostfixとして私の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]); 
+0

あなたは文字通り私の答えを別の方法で書き直しただけでなく、これを考慮しましたか?両方の文字列がnilの場合、長さ== 0で、位置0はそれらが異なる位置であることを示します。 – Vikings

+1

メソッドが呼び出された文字列がnilの場合、私のメソッドは0を返します。両方の文字列をゼロにする必要はありません。このケースでは、nilに送られたメッセージは何も返さないので、あなたができることはあまりありません。あなたのバージョンの問題は、2つの文字列が同じステムを持ち、もう一方が長い場合は-1を返します。私はあなたのバージョンを修正するのを手伝ってくれました。あなたがそれを悪化させたと私の意見では、私は自分の答えで踏み込んだのです。私はあなたの答えを盗んだと感じたらごめんなさい。 – mttrb

+0

+1私はそのような問題を見ていませんでした。また、あなたには余分な ';'長い整数 "%ld"を出力しないでください。 – Vikings

3

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

+0

ですアイデアは、私はそれが簡単な方法だと思いますか? –

+0

簡単な方法は、これを行うためにNSStringクラスのメソッドフォームを使用することです。内部的にはこれと同じ戦略を使用します。残念ながら、このメソッドは存在しないので、自分で記述する必要があります。 – sidyll

+0

それは簡単な方法です、タスクはあまり複雑ではありません。 – Alexander

1

-rangeOfString:を使用できます。たとえば、[string rangeOfString:@"l"].locationです。この方法にはいくつかのバリエーションがあります。

関連する問題