0

我有一些我想在某个时候替换的 html 代码。

NSString *stringSHOW = @"width="353" height="500" width="131" height="204" width="777" width="369" width="888"/>";

像这样的东西。但我想全部替换[ width="any" to width="300" ]

有没有办法做到这一点?

4

3 回答 3

2

查看NSRegularExpression的文档和NSString采用正则表达式的方法。

于 2012-07-06T06:49:38.057 回答
0
NSString *newStringShow = [stringShow stringByReplacingOccurrencesOfString:@"any"withString:@"300"];
于 2012-07-06T06:53:45.443 回答
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"];

您还可以将分隔符字符串作为参数发送,在您的情况下为 @"width=\"" 和 @"\"" 以使此方法完全抽象并能够替换您传递的任何内容。

于 2012-07-06T08:55:55.310 回答