2012-04-21 4 views

답변

2

나는 당신이 원하는 것을 할 수있는 NSString에 카테고리를 작성했습니다. 내 StackOverflow 사용자 이름을 범주 메서드의 접미사로 사용했습니다. 이것은 같은 이름의 메소드와 충돌 할 가능성이 낮을 가능성을 막기위한 것입니다. 자유롭게 변경하십시오.

먼저 인터페이스 정의 NSString+Difference.h :

#import <Foundation/Foundation.h> 

@interface NSString (Difference) 

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

@end 

및 구현 '는 NSString + Difference.m` :

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

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

당신은 말 그대로 내 대답을 다른 방식으로 다시 작성했을뿐만 아니라 이것을 고려했습니다. 두 문자열이 모두 nil 인 경우 length == 0으로 위치 0이 서로 다른 위치임을 나타냅니다. – Vikings

+1

메서드가 호출 된 문자열이 nil이면 내 메서드가 0을 반환하는 것이 맞습니다. 두 문자열이 모두 필요하지 않습니다. nil에게 보낸 메시지가 아무 것도 반환하지 않으므로이 경우에는 할 수있는 일이 많지 않습니다. 귀하의 버전 문제는 두 개의 문자열이 동일한 줄기가 있지만 다른 줄보다 길면 -1을 반환한다는 것입니다. 나는 당신이 당신의 버전을 고치는 것을 도우려고 노력했다. 그리고 나의 의견으로는 당신은 그것을 나쁘게 만들었다. 그래서 나는 나 자신의 대답으로 들어갔다. 나는 당신의 대답을 훔쳤다면 미안합니다. – mttrb

+0

+1 나는 그런 식으로 문제를 보지 않고 있었다. 또한, 당신은 관계없는 ';' 긴 정수 "% ld"를 출력해서는 안됩니다. – Vikings

3

한 문자열을 통해 시작하여 다른 문자열의 동일한 색인에있는 문자와 각 문자를 비교하십시오. 비교가 실패한 곳은 변경된 문자의 색인입니다.

+0

가되어 다음과 같이

#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 

당신은 위의를 사용합니다 아이디어, 그러나 나는 그것이 쉬운 방법이라고 생각하지 않습니까? –

+0

쉬운 방법은 내부적으로 매우 동일한 전략을 사용하는 NSString 클래스의 메소드 양식을 사용하는 것입니다. 불행하게도이 방법은 존재하지 않으므로 직접 작성해야합니다. – sidyll

+0

그것은 쉬운 방법입니다, 작업은 매우 복잡하지 않습니다. – Alexander

1

-rangeOfString:을 사용할 수 있습니다. 예 : [string rangeOfString:@"l"].location. 이 방법에는 몇 가지 변형이 있습니다.