[英]Replace part of a NSString from an NSarray of dictionary with Key A with a string in same NSarray of dictionary with Key B
我有以下格式的字典数组。
mainArray[0] = { "key1" : "aText", "key2" :"Text to replace A" }
mainArray[1] = { "key1" : "bText", "key2" :"Text to replace B" }
等等。
我有一个nsstring,可以包含任何随机文本。 但是,如果字符串中出现“ aText”,则必须用相应的key2值替换为“ Text to replace A”,并且对于数组的其余部分也类似。
仅通过使用nspredicates / 而不进行任何循环,如何做到这一点?
注意:
我当前的解决方案如下:
NSArray arrayForKey1 = [mainArray valueForKey:@"key1"];
NSArray arrayForKey2 = [mainArray valueForKey:@"key2"];
for (int i = 0; i < mainArray.count; i ++) {
MyString = [MyString stringByReplacingOccurrencesOfString : [arrayForKey1 objectAtIndex:i]
withString : [arrayForKey2 objectAtIndex:i]
options : NSCaseInsensitiveSearch
range : NSMakeRange(0, MyString.length)
];
}
如果要将aText
映射到Text to replace a
则key1
和key2
键没有用。
您可能拥有的是:
NSMutableString *input = [@"aText apple bText banana cText carrot" mutableCopy];
NSDictionary *replacements = { @"aText" : @"Text to replace a",
@"bText" : @"Text to replace b",
@"cText" : @"Text to replace c" };
for (NSString *rep in replacements)
{
[input replaceOccurrencesOfString:rep withString:[replacements objectForKey:rep]];
}
只要替换字符串不包含任何搜索字符串,这将起作用,否则替换两次即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.