To solve this problem, I recommend creating a category:
@interface NSString (AdditionalMethods) - (NSString* _Nonnull)withFirstCharLowercasedLastCharUppercased; - (NSString* _Nonnull)withFirstCharLowercasedLastCharUppercasedForEachWord; @end
The withFirstCharLowercasedLastCharUppercased
method makes the first lowercase letter, the last one - uppercase:
- (NSString* _Nonnull)withFirstCharLowercasedLastCharUppercased { if (self.length == 0) { return self; } NSMutableString* result = [[NSMutableString alloc] initWithString:self]; [result replaceCharactersInRange:NSMakeRange(0, 1) withString:[self substringToIndex:1].lowercaseString]; [result replaceCharactersInRange:NSMakeRange(self.length - 1, 1) withString:[self substringFromIndex:self.length - 1].uppercaseString]; return result; }
The withFirstCharLowercasedLastCharUppercasedForEachWord
method calls withFirstCharLowercasedLastCharUppercased
for each word, and then replaces it in the source line:
- (NSString* _Nonnull)withFirstCharLowercasedLastCharUppercasedForEachWord { NSMutableString *result = [[NSMutableString alloc] initWithString:self]; [self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { [result replaceCharactersInRange:substringRange withString:substring.withFirstCharLowercasedLastCharUppercased]; }]; return result; }
Example of use:
NSString* text = @"The NSString class declares the programmatic interface for an object that manages immutable strings. An immutable string is a text string that is defined when it is created and subsequently cannot be changed."; NSLog(@"%@", text.withFirstCharLowercasedLastCharUppercasedForEachWord); // выводит "thE nSStrinG clasS declareS thE programmatiC interfacE foR aN objecT thaT manageS immutablE stringS. aN immutablE strinG iS A texT strinG thaT iS defineD wheN iT iS createD anD subsequentlY cannoT bE changeD."