1

好的,假设我有字符串“ hello my name is donald

现在,我想删除从“ hello”到“ is”的所有内容,“ my name”可以是任何东西,也可以是“ his son

所以基本上,简单地做是stringByReplacingOccurrencesOfString行不通的。

(我确实有 RegexLite)

我该怎么做?

4

3 回答 3

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);
于 2012-07-16T10:34:37.987 回答
0

如果您总是知道您的字符串将以 'hello my name is ' 开头,那么包括最后一个空格在内的 17 个字符,所以如果您

NSString * hello = "hello my name is Donald Trump";
NSString * finalNameOnly = [hello substringFromIndex:17];
于 2012-07-16T15:50:51.440 回答
0

以下 NSString 类别可能会对您有所帮助。它对我有用,但不是我创造的。感谢作者。

NSString+Whitespace.h

#import <Foundation/Foundation.h>

@interface NSString (Whitespace)

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

@end

NSString+空格.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
于 2012-07-16T10:01:42.960 回答