开发者

Replacing string between two string iphone sdk

开发者 https://www.devze.com 2023-01-19 09:31 出处:网络
in objective c 开发者_JAVA技巧i want to replace string which is between two string. For example \"ab anystring yz\"

in objective c 开发者_JAVA技巧i want to replace string which is between two string.

For example "ab anystring yz"

i want to replace string which is between "ab" and "yz".

is it possible to do? Please Help

thx in advance.


Here is tested code to perform your task.

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"];
    }
}

Now you just check the string you will get ab Replace string yz


NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfString:@"anystring" withString:@""];

otherwise you're going to have to get a copy of REGEXKitLite and use a regex function like:

NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfRegex:@"ab\\b.\\byz" withString:@"ab yz"];


    -(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) {
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消