How do i remove a substring from an nsstring?

Ok, say I have the string "hello my name is donald"

Now, I want to remove everything from "hello" to "is" The thing is, "my name" could be anything, it could also be "his son"

So basically, simply doing stringByReplacingOccurrencesOfString won't work.

(I do have RegexLite)

How would I do this?

Answers


Use like below it will help you

NSString *hello = @"his is name is isName";
NSRange rangeSpace = [hello rangeOfString:@" " 
                                  options:NSBackwardsSearch];
NSRange isRange = [hello rangeOfString:@"is" 
                               options:NSBackwardsSearch 
                                 range:NSMakeRange(0, rangeSpace.location)];

NSString *finalResult = [NSString stringWithFormat:@"%@ %@",[hello substringToIndex:[hello rangeOfString:@" "].location],[hello substringFromIndex:isRange.location]];
NSLog(@"finalResult----%@",finalResult);

The following NSString Category may help you. It works good for me but not created by me. Thanks for the author.

NSString+Whitespace.h

#import <Foundation/Foundation.h>

@interface NSString (Whitespace)

- (NSString *)stringByCompressingWhitespaceTo:(NSString *)seperator;

@end

NSString+Whitespace.m

#

import "NSString+Whitespace.h"

@implementation NSString (Whitespace)
- (NSString *)stringByCompressingWhitespaceTo:(NSString *)seperator
{
    //NSArray *comps = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSArray *comps = [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    NSMutableArray *nonemptyComps = [[NSMutableArray alloc] init];

    // only copy non-empty entries
    for (NSString *oneComp in comps)
    {
        if (![oneComp isEqualToString:@""])
        {
            [nonemptyComps addObject:oneComp];
        }

    }

    return [nonemptyComps componentsJoinedByString:seperator];  // already marked as autoreleased
}
@end

If you always know your string will begin with 'hello my name is ', then that is 17 characters, including the final space, so if you

NSString * hello = "hello my name is Donald Trump";
NSString * finalNameOnly = [hello substringFromIndex:17];

Need Your Help

Running unit tests before each build in Gradle

android unit-testing gradle build.gradle

How can I configure a build.gradle in an Android project to run all my unit tests before each debug or release build? I know that I can set tasks dependencies with dependsOn, but how can I specify ...

iOS app getting crashed while opening after force closing the app

ios iphone objective-c

I am using https://github.com/vfr/Reader sample for viewing PDF files. If i normally opens the app some times it is getting crash. If i force close the app by double pressing home button, then open...