如果文本太長,這可能是有點慢但它的工作原理。使用正則表達式解決方案。
NSString *string = @"Example This is a string \"with quoted1\" text and there is \"some more1\" quoted text. I want to be able to turn this string into the following: This is a string \"with quoted2\" text and there is \"some more2\" quoted text.";
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string attributes:nil];
int leftFromLeft = 0;
while ([string rangeOfString:@"\""].location != NSNotFound) {
NSRange quoteLocationFirst = [string
rangeOfString:@"\""
options:0
range:NSMakeRange(leftFromLeft, string.length - leftFromLeft)
];
leftFromLeft = quoteLocationFirst.location + quoteLocationFirst.length;
NSRange quoteLocationSecond = [string
rangeOfString:@"\""
options:0
range:NSMakeRange(leftFromLeft, string.length - leftFromLeft)
];
NSRange quotedTextRange = NSMakeRange(
quoteLocationFirst.location,
quoteLocationSecond.location - quoteLocationFirst.location + 1
);
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
[attString addAttribute:NSFontAttributeName value:font range:quotedTextRange];
NSLog(@"%@ \r\n\r\n", [string substringWithRange:quotedTextRange]);
leftFromLeft = quoteLocationSecond.location + quoteLocationSecond.length;
if ([string rangeOfString:@"\"" options:0 range:NSMakeRange(leftFromLeft, string.length - leftFromLeft)].location == NSNotFound) {
string = @"";
}
}
編輯
正則表達式的解決方案似乎是更好/更快。
NSString *string = @"Example This is a string \"with quoted1\" text and there is \"some more1\" quoted text. I want to be able to turn this string into the following: This is a string \"with quoted2\" text and there is \"some more2\" quoted text. Example This is a string \"with quoted3\" text and there is \"some more3\" quoted text. I want to be able to turn this string into the following: This is a string \"with quoted4\" text and there is \"some more4\" quoted text.";
NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string attributes:nil];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\"([^\"]*)\"" options:NSRegularExpressionCaseInsensitive error:nil];
NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
for (NSTextCheckingResult *match in arrayOfAllMatches) {
UIFont *font = [UIFont fontWithName:@"Helvetica-Bold" size:30.0f];
[attString addAttribute:NSFontAttributeName value:font range:match.range];
//NSLog(@"%@", [string substringWithRange:match.range]);
}
您是否聽說過NSRegularExpression? – matt