2012-06-23 2 views
5

NSString을 반복하고 특정 조건 (예 : "2"L '있음)이있는 모든 단어에 대해 사용자 지정 함수를 호출하고 싶습니다. 나는 그것에 접근하는 가장 좋은 방법이 무엇인지 궁금해하고 있었다. 찾기/바꾸기 패턴을 사용해야합니까? 블록?NSString의 모든 단어에 대한 메서드 호출

-(NSString *)convert:(NSString *)wordToConvert{ 
    /// This I have already written 
    Return finalWord; 
} 

-(NSString *) method:(NSString *) sentenceContainingWords{ 
    // match every word that meets the criteria (for example the 2Ls) and replace it with what convert: does. 
} 

답변

2

두 가지 방법은 다음과 같습니다

NSArray *words = [sentence componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 

for (NSString *word in words) 
{ 
    NSString *transformedWord = [obj method:word]; 
} 

NSArray *words = [sentence componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 

[words enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id word, NSUInteger idx, BOOL *stop){ 
    NSString *transformedWord = [obj method:word]; 
}]; 

다른 방법, –makeObjectsPerformSelector:withObject:

은, 당신을 위해 작동하지 않습니다. 예상보다 뒤쪽에있는 [word method:obj] 번으로 전화 할 수 있습니다.

+0

중국어, 일본어, 독일어와 같은 일부 언어의 경우 공백은 단어 사이의 명확한 제한자가 아니므로 켄 접근 방식이 적절합니다. – Krodak

1

당신이 정규 표현식을 사용하여 기준을 쓸 수 있다면, 당신은 아마이 말을 인출 한 다음 convert: 메소드에 전달 일치하는 정규 표현식을 할 수 있습니다.

componentsSeparatedByString: 또는 componentsSeparatedByCharactersInSet:을 사용하여 단어 배열로 문자열을 분할 한 다음 배열의 단어로 이동하여 어떻게 든 귀하의 기준에 맞는 지 검색 할 수 있습니다. 적합하면 convert:으로 전달하십시오.

희망이 도움이됩니다.

-1

while 루프를 사용하여 다음과 같은 문자열을 사용하는 것이 좋습니다.

NSRange spaceRange = [sentenceContainingWords rangeOfString:@" "]; 
NSRange previousRange = (NSRange){0,0}; 
do { 
    NSString *wordString; 
    wordString = [sentenceContainingWord substringWithRange:(NSRange){previousRange.location+1,(spaceRange.location-1)-(previousRange.location+1)}]; 
    //use the +1's to not include the spaces in the strings 
    [self convert:wordString]; 
    previousRange = spaceRange; 
    spaceRange = [sentenceContainingWords rangeOfString:@" "]; 
} while(spaceRange.location != NSNotFound); 

이 코드는 꽤 거칠기 때문에 다시 작성해야 할 필요가 있지만 아이디어를 얻어야합니다.

편집 : 제이콥 고르반 (Jacob Gorban)의 게시물을 보았을 때 분명히 그렇게해야합니다. 다음과 같이 내가 당신을 위해 작동 배열을 반복 알고

18

문자열의 단어를 열거하려면 NSStringEnumerationByWordsNSStringEnumerationLocalized과 함께 -[NSString enumerateSubstringsInRange:options:usingBlock:]을 사용해야합니다. 나열된 다른 모든 방법은 로케일에 적합하지 않거나 시스템 정의에 해당하는 단어를 식별하는 방법을 사용합니다. 예를 들어 공백이 아닌 쉼표로 구분 된 두 단어 (예 : 'foo, bar')는 다른 답변에 의해 별도의 단어로 취급되지 않지만 코코아 텍스트보기에 있습니다. 당신이 변경 가능한 문자열을 호출하면, 당신은 안전하게 문자열을 변이 할 수 -enumerateSubstringsInRange:options:usingBlock:에 대한 설명으로

[aString enumerateSubstringsInRange:NSMakeRange(0, [aString length]) 
          options:NSStringEnumerationByWords | NSStringEnumerationLocalized 
         usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){ 
    if ([substring rangeOfString:@"ll" options:NSCaseInsensitiveSearch].location != NSNotFound) 
     /* do whatever */; 
}]; 

enclosingRange을 열거된다. 따라서 일치하는 단어를 바꾸려면 [aString replaceCharactersInRange:substringRange withString:replacementString]과 같이 할 수 있습니다.

관련 문제