我有一些html代码,我想在某些时候替换它。
如
NSString *stringSHOW = @"width="353" height="500" width="131" height="204" width="777" width="369" width="888"/>";
像这样的东西。但我想替换所有[ width="any" to width="300" ]
。
有没有办法做到这一点?
答案 0 :(得分:2)
查看NSRegularExpression的文档和采用正则表达式的NSString
方法。
答案 1 :(得分:0)
NSString *newStringShow = [stringShow stringByReplacingOccurrencesOfString:@"any"withString:@"300"];
答案 2 :(得分:0)
- (NSString *)updateString:(NSString *)inputString withString:(NSString *)stringToReplace {
NSArray *components = [inputString componentsSeparatedByString:@" "];
NSMutableArray *mutableComponents = [[components mutableCopy] autorelease];
for (NSString *componentString in components) {
NSMutableString *mutableString = [[componentString mutableCopy] autorelease];
NSRange replaceRangeFirstOccurenceStart = [mutableString rangeOfString:@"width=\""];
if (replaceRangeFirstOccurenceStart.location == NSNotFound) {
NSLog(@"String not found in component");
}
NSMutableString *replaceString = [NSMutableString string];
for (int i = 0; i < replaceRangeFirstOccurenceStart.length; i ++) {
[replaceString appendString:@"_"];
}
NSMutableString *modifiedString = [mutableString stringByReplacingCharactersInRange:replaceRangeFirstOccurenceStart withString:replaceString];
NSRange replaceRangeEnd = [modifiedString rangeOfString:@"\""];
NSRange rangeToChange = NSMakeRange(replaceRangeFirstOccurenceStart.length - 1, replaceRangeEnd.location + replaceRangeEnd.length - replaceRangeFirstOccurenceStart.length + 1);
NSString *updatedString = [mutableString stringByReplacingCharactersInRange:rangeToChange withString:[NSString stringWithFormat:@"\"%@\"", stringToReplace]];
[mutableComponents replaceObjectAtIndex:[components indexOfObject:componentString] withObject:updatedString];
}
return [mutableComponents componentsJoinedByString:@" "];
}
NSString *stringShow = @"width=\"355\" width=\"200\"";
[self updateString:stringShow withString:@"34501"];
你也可以发送params作为参数字符串,在你的情况下@“width = \”“和@”\“”,以使这个方法完全抽象,并能够替换你传递的任何东西。