如何从字符串中删除单词

时间:2012-05-23 06:04:20

标签: iphone ios nsstring

你好,我是objective-c的初学者 我有这样的nsstring

Select *  from Store_Master where AND  VDivison = 'Casual Dining' AND VBrand_Name = 'Pinkberry' AND VCountry_Name = 'Egypt' AND VCity = 'Cairo' AND VBuilding_mall_name = 'Dandy Mega Mall' GROUP BY VStore_Name

我想删除AND的第一次出现,我该如何删除。

提前谢谢

3 个答案:

答案 0 :(得分:3)

使用stringByReplacingCharactersInRange仅替换第一个' AND':

NSString* s = @"Select *  from Store_Master where AND  VDivison = 'Casual Dining' AND VBrand_Name = 'Pinkberry' AND VCountry_Name = 'Egypt' AND VCity = 'Cairo' AND VBuilding_mall_name = 'Dandy Mega Mall' GROUP BY VStore_Name";
NSRange replaceRange = [s rangeOfString:@"AND"];
if (replaceRange.location != NSNotFound){
    NSString* result = [s stringByReplacingCharactersInRange:replaceRange withString:@""];
}

这将导致:

Select *  from Store_Master where   VDivison = 'Casual Dining' AND VBrand_Name = 'Pinkberry' AND VCountry_Name = 'Egypt' AND VCity = 'Cairo' AND VBuilding_mall_name = 'Dandy Mega Mall' GROUP BY VStore_Name

编辑:

如果要以不区分大小写的方式删除AND的出现(无论小写的大写),请在创建NSRange时使用NSStringCompareOptions,如下所示:

NSRange replaceRange = [s rangeOfString:@"and" options:NSCaseInsensitiveSearch];

其余代码是相同的。

答案 1 :(得分:0)

NSString *String1 = @"Select *  from Store_Master where AND  VDivison = 'Casual Dining' AND VBrand_Name = 'Pinkberry' AND VCountry_Name = 'Egypt' AND VCity = 'Cairo' AND VBuilding_mall_name = 'Dandy Mega Mall' GROUP BY VStore_Name";
NSString *String2 = [String1 stringByReplacingOccurrencesOfString:@"AND" withString:@""];



NSString * aString  = @"Select *  from Store_Master where AND  VDivison = 'Casual Dining' AND VBrand_Name = 'Pinkberry' AND VCountry_Name = 'Egypt' AND VCity = 'Cairo' AND VBuilding_mall_name = 'Dandy Mega Mall' GROUP BY VStore_Name";
NSRange replaceRange = [aString rangeOfString:@"AND"];
if (replaceRange.location !=NSNotFound){
    NSString * newString = [aString stringByReplacingCharactersInRange:replaceRange withString:@""];
    NSLog(newString);
}

答案 2 :(得分:0)

NSString *s = @"your string";
NSInteger loc = [s rangeOfString: @"AND"].location;
if (loc != NSNotFound) s = [NSString stringWithFormat: @"%@%@", [s substringToIndex: loc], [s substringFromIndex: loc + 3]];

这将删除第一次出现的AND。第二行找到第一次出现的位置。第三行获取前后子串,并使用stringWithFormat将它们放在一起。

获取位置后,还有其他方法可以删除它,例如使用stringByReplacingCharactersInRange给定范围的find-replace,或者像我的示例一样,但使用stringByAppendingString连接部分。