代码之家  ›  专栏  ›  技术社区  ›  Viral Narshana

在两个字符串iphone sdk之间替换字符串

  •  0
  • Viral Narshana  · 技术社区  · 14 年前

    在目标C中,我想替换两个字符串之间的字符串。

    例如 “AB AnyString YZ”

    我想替换“ab”和“yz”之间的字符串。

    有可能吗?请帮助

    提前通知。

    3 回复  |  直到 8 年前
        1
  •  2
  •   Thomas Clayson    14 年前
    NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfString:@"anystring" withString:@""];
    

    REGEXKitLite

    NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfRegex:@"ab\\b.\\byz" withString:@"ab yz"];
    
        2
  •  4
  •   Muhammad Rizwan    10 年前

    NSString *string = @"ab anystring yz";
    NSString *result = nil;
    // Determine "ab" location
    NSRange divRange = [string rangeOfString:@"ab" options:NSCaseInsensitiveSearch];
    if (divRange.location != NSNotFound)
    {
        // Determine "ab" location according to "yz" location
        NSRange endDivRange;
    
        endDivRange.location = divRange.length + divRange.location;
        endDivRange.length   = [string length] - endDivRange.location;
        endDivRange = [string rangeOfString:@"yz" options:NSCaseInsensitiveSearch range:endDivRange];
    
        if (endDivRange.location != NSNotFound)
        {
            // Tags found: retrieve string between them
            divRange.location += divRange.length;
            divRange.length = endDivRange.location - divRange.location;
    
            result = [string substringWithRange:divRange];
    
            string =[string stringByReplacingCharactersInRange:divRange withString:@"Replace string"];
        }
    }
    

        3
  •  -1
  •   Sushibu Sadanandan    8 年前
        -(NSString*)StrReplace :(NSString*)mainString preMatch:(NSString*) preMatch postMatch:(NSString*) postMatch replacementString:(NSString*) replacementString
        {
            @try
    
            {
    
                if (![mainString isEqualToString:@""] || [mainString isKindOfClass:[NSNull class]] || mainString==nil)
                {
    
    
                    NSArray *preSubstring = [mainString componentsSeparatedByString:preMatch];
                    NSString *preStr = [preSubstring objectAtIndex:0];
    
                    NSArray *postSubstring = [mainString componentsSeparatedByString:postMatch];
                    NSString *postStr = [postSubstring objectAtIndex:1];
    
                    NSString *resultStr = [NSString stringWithFormat:@"%@%@%@%@%@" ,preStr,preMatch,replacementString,postMatch,postStr];
    
                    return resultStr;
    
                }
                else
                {
                    return @"";
                }
    
            }
            @catch (NSException *exception) {
            }
        }