【发布时间】:2011-04-22 19:23:56
【问题描述】:
在目标 c 我想替换两个字符串之间的字符串。
例如 "ab anystring yz"
我想替换“ab”和“yz”之间的字符串。
有可能吗?请帮忙
提前谢谢。
【问题讨论】:
标签: iphone iphone-sdk-3.0 ios-simulator
在目标 c 我想替换两个字符串之间的字符串。
例如 "ab anystring yz"
我想替换“ab”和“yz”之间的字符串。
有可能吗?请帮忙
提前谢谢。
【问题讨论】:
标签: iphone iphone-sdk-3.0 ios-simulator
这是执行任务的经过测试的代码。
NSString *string = @"ab anystring yz";
NSString *result = nil;
// Determine "ab" location
NSRange divRange = [string rangeOfString:@"ab" options:NSCaseInsensitiveSearch];
if (divRange.location != NSNotFound)
{
// Determine "ab" location according to "yz" location
NSRange endDivRange;
endDivRange.location = divRange.length + divRange.location;
endDivRange.length = [string length] - endDivRange.location;
endDivRange = [string rangeOfString:@"yz" options:NSCaseInsensitiveSearch range:endDivRange];
if (endDivRange.location != NSNotFound)
{
// Tags found: retrieve string between them
divRange.location += divRange.length;
divRange.length = endDivRange.location - divRange.location;
result = [string substringWithRange:divRange];
string =[string stringByReplacingCharactersInRange:divRange withString:@"Replace string"];
}
}
现在您只需检查您将得到的字符串 ab 替换字符串 yz
【讨论】:
NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfString:@"anystring" withString:@""];
否则,您将不得不获取REGEXKitLite 的副本并使用正则表达式函数,例如:
NSString *newString = [(NSString *)yourOldString stringByReplacingOccurrencesOfRegex:@"ab\\b.\\byz" withString:@"ab yz"];
【讨论】:
. 表示“任意数量的字符”。您需要下载 regexKitLite 并将其包含在您的项目中。
NSString *str = [[NSString alloc] init]; str= @"Hello";,您可以直接使用:NSString *str = [NSString stringWithFormat:@"Hello"];,这样您就不必担心内存管理或其他任何事情。 :) 而且它的编码和阅读更好一点。 :)
-(NSString*)StrReplace :(NSString*)mainString preMatch:(NSString*) preMatch postMatch:(NSString*) postMatch replacementString:(NSString*) replacementString
{
@try
{
if (![mainString isEqualToString:@""] || [mainString isKindOfClass:[NSNull class]] || mainString==nil)
{
NSArray *preSubstring = [mainString componentsSeparatedByString:preMatch];
NSString *preStr = [preSubstring objectAtIndex:0];
NSArray *postSubstring = [mainString componentsSeparatedByString:postMatch];
NSString *postStr = [postSubstring objectAtIndex:1];
NSString *resultStr = [NSString stringWithFormat:@"%@%@%@%@%@" ,preStr,preMatch,replacementString,postMatch,postStr];
return resultStr;
}
else
{
return @"";
}
}
@catch (NSException *exception) {
}
}
【讨论】: