Viral Narshana
Viral Narshana

Reputation: 1877

Replacing string between two string iphone sdk

in objective c 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.

Upvotes: 0

Views: 1786

Answers (3)

Sushibu Sadanandan
Sushibu Sadanandan

Reputation: 1

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

Upvotes: -1

Muhammad Rizwan
Muhammad Rizwan

Reputation: 3480

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

Upvotes: 4

Thomas Clayson
Thomas Clayson

Reputation: 29925

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

Upvotes: 2

Related Questions