Reputation: 3
I have some html code that I want to replace at some point.
Such as
NSString *stringSHOW = @"width="353" height="500" width="131" height="204" width="777" width="369" width="888"/>";
Something like this. But I want to replace all [ width="any" to width="300" ]
.
Is there any way to do this ?
Upvotes: 0
Views: 151
Reputation: 3366
- (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"];
You can also send as params the delimiters strings, in your case @"width=\"" and @"\"" to make this method entirely abstract and to be able to replace anything you pass it.
Upvotes: 0
Reputation: 8163
NSString *newStringShow = [stringShow stringByReplacingOccurrencesOfString:@"any"withString:@"300"];
Upvotes: 0
Reputation: 126167
Take a look at the docs for NSRegularExpression and the NSString
methods which take regular expressions.
Upvotes: 2