如何从string中删除单词

你好我是一个初学者在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的第一个出现,我怎么删除。

先谢谢你

使用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 (不区分大小写),请在创buildNSRange时使用NSStringCompareOptions ,如下所示:

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

其余的代码是一样的。

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

希望对你有帮助…

 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查找replace范围,或者像我的示例那样执行,但是使用stringByAppendingString来连接部分。