好的,我说我有字符串“hello my name is donald
”
现在,我要删除从“hello
”到“is
”的所有内容
问题是,“my name
”可以是任何内容,也可以是“his son
”
基本上,简单地执行stringByReplacingOccurrencesOfString
将无效。
(我确实有RegexLite)
我该怎么做?
答案 0 :(得分: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);
答案 1 :(得分: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
答案 2 :(得分:0)
如果你总是知道你的字符串将以'你好我的名字'开头,那么这是17个字符,包括最后的空格,所以如果你
NSString * hello = "hello my name is Donald Trump";
NSString * finalNameOnly = [hello substringFromIndex:17];