How do i remove a substring from an nsstring?

此生再无相见时 提交于 2019-12-08 06:11:34

问题


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?


回答1:


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);



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/11502015/how-do-i-remove-a-substring-from-an-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!