2012-07-16 59 views
1

好吧,說我有字符串「hello my name is donald我如何從nsstring中刪除子字符串?

現在,我想從「hello」刪除一切「is」 的事情是,「my name」可以是任何東西,也有可能是「his son

所以基本上,只是做stringByReplacingOccurrencesOfString將無法​​正常工作。

(我有RegexLite)

我會怎麼做呢?

+0

如果子是永遠不變的,你不」不需要,你不應該爲此使用正則表達式。 – m0skit0 2012-07-16 09:57:45

+0

你不認真?我;只是用這個字符串作爲例子!返回@「唐納德」幫助沒有人,而不是這個問題的重點 – maor10 2012-07-16 22:37:38

回答

2

使用如下它會幫助你

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

以下NSString類別可能會對您有所幫助。它適用於我,但不是由我創建的。感謝作者。

的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 
0

如果你總是知道你的字符串將開始「我的名字是」,然後就是17個字符,包括最後的空間,因此,如果您

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