我有一些我想在某个时候替换的 html 代码。
如
NSString *stringSHOW = @"width="353" height="500" width="131" height="204" width="777" width="369" width="888"/>";
像这样的东西。但我想全部替换[ width="any" to width="300" ]
。
有没有办法做到这一点?
查看NSRegularExpression的文档和NSString
采用正则表达式的方法。
NSString *newStringShow = [stringShow stringByReplacingOccurrencesOfString:@"any"withString:@"300"];
- (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"];
您还可以将分隔符字符串作为参数发送,在您的情况下为 @"width=\"" 和 @"\"" 以使此方法完全抽象并能够替换您传递的任何内容。