문자열의 특정 단어를 가져오고 바꾸는 가장 좋은 방법은 무엇입니까? 내가 가진 예를 들어 는NSString의 특정 단어 바꾸기
NSString * currentString = @"one {two}, thing {thing} good";
지금 나는
[self replaceWord:currentWord]
다음 기능
-(NSString*)replaceWord:(NSString*)currentWord;
문자열의 특정 단어를 가져오고 바꾸는 가장 좋은 방법은 무엇입니까? 내가 가진 예를 들어 는NSString의 특정 단어 바꾸기
NSString * currentString = @"one {two}, thing {thing} good";
지금 나는
[self replaceWord:currentWord]
다음 기능
-(NSString*)replaceWord:(NSString*)currentWord;
에서 결과 currentWord을 대체하기위한 기능을 각각 {currentWord}을 (를) 찾을 수
및 적용 필요 다음 예는 NSRegularExpression
을 사용하는 방법을 보여줍니다. 작업을 완료하려면 enumerateMatchesInString
을 입력하십시오. 난 그냥 단어를 대체 함수로 uppercaseString
를 사용했다,하지만 당신은뿐만 아니라 당신의 replaceWord
방법을 사용할 수 있습니다 :
편집 : 대체 단어 짧거나 긴 같은 경우 내 대답의 첫 번째 버전이 제대로 작동하지 않았다 원래의 단어 (Fabian Kreiser 덕분에 주목!). 이제는 모든 경우에 올바르게 작동해야합니다.
NSString *currentString = @"one {two}, thing {thing} good";
// Regular expression to find "word characters" enclosed by {...}:
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:@"\\{(\\w+)\\}"
options:0
error:NULL];
NSMutableString *modifiedString = [currentString mutableCopy];
__block int offset = 0;
[regex enumerateMatchesInString:currentString
options:0
range:NSMakeRange(0, [currentString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
// range = location of the regex capture group "(\\w+)" in currentString:
NSRange range = [result rangeAtIndex:1];
// Adjust location for modifiedString:
range.location += offset;
// Get old word:
NSString *oldWord = [modifiedString substringWithRange:range];
// Compute new word:
// In your case, that would be
// NSString *newWord = [self replaceWord:oldWord];
NSString *newWord = [NSString stringWithFormat:@"--- %@ ---", [oldWord uppercaseString] ];
// Replace new word in modifiedString:
[modifiedString replaceCharactersInRange:range withString:newWord];
// Update offset:
offset += [newWord length] - [oldWord length];
}
];
NSLog(@"%@", modifiedString);
출력 :
one {--- TWO ---}, thing {--- THING ---} good
감사합니다! 꽤 잘 작동합니다. – user840250
@ user840250 : 오신 것을 환영합니다. –
대체 단어가 원래 단어보다 짧거나 길 때 코드가 작동하지 않습니다. –
당신이 내 {및} 각 단어를 바꾸시겠습니까? –
은 {} 에 어떤 단어가 들어 있는지에 따라 다르므로 {word}를 찾아 단어를 잘라내 어서 바꾸십시오. – user840250
불완전한 질문. plz 당신이 정확히 원하는 것을 설명하십시오. 어떤 무늬를 찾으려고 wnat –