[英]Replace part of a NSString from an NSarray of dictionary with Key A with a string in same NSarray of dictionary with Key B
I have an array of dictionary in the following format. 我有以下格式的字典数组。
mainArray[0] = { "key1" : "aText", "key2" :"Text to replace A" }
mainArray[1] = { "key1" : "bText", "key2" :"Text to replace B" }
and so on. 等等。
I have an nsstring which can contain any random text. 我有一个nsstring,可以包含任何随机文本。 But if there is an occurrence of "aText" in the string it has to be replaced with the corresponding key2 value as "Text to replace A" and similarly for the rest of the array. 但是,如果字符串中出现“ aText”,则必须用相应的key2值替换为“ Text to replace A”,并且对于数组的其余部分也类似。
How can this be done just by using nspredicates / with out any looping? 仅通过使用nspredicates / 而不进行任何循环,如何做到这一点?
NOTE: 注意:
My current solution is as follows: 我当前的解决方案如下:
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)
];
}
The key1
and key2
keys are useless if you want to map aText
to Text to replace a
. 如果要将aText
映射到Text to replace a
则key1
和key2
键没有用。
What you could have is: 您可能拥有的是:
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]];
}
This will work as long as the replacement strings do not contain any of the search strings, otherwise they could be replaced twice. 只要替换字符串不包含任何搜索字符串,这将起作用,否则替换两次即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.