我需要检查字符串的开头和结尾是否包含任何逗号(,)并删除逗号(或)用空字符串替换这些逗号。
例如,
NSString *str1 = @",a,b,c,d,"; or
NSString *str1 = @",a,b,c,d"; or
NSString *str1 = @"a,b,c,d,";
输出:
NSString *str1 = @"a,b,c,d";
我试过这个
NSRange lastComma = [str1 rangeOfString:@"," options:NSBackwardsSearch];
if(lastComma.location != NSNotFound) {
str1 = [str1 stringByReplacingCharactersInRange:lastComma
withString: @""];
}
并删除最后一个逗号,但如何删除第一个逗号?。
有没有办法做到这一点,欢迎帮助。
答案 0 :(得分:3)
您可以使用[NSString componentsSeparatedByString:]
然后拒绝所有空字符串。这样就可以删除列表中的空元素:
NSArray *elements = [inputString componentsSeparatedByString:@","];
NSMutableArray *outputElements = [[NSMutableArray alloc] init];
for (NSString *element in elements)
if ([element length] > 0)
[outputElements addObject:element];
然后重新格式化字符串:
NSString *outputString = [outputElements componentsJoinedByString:@","]
答案 1 :(得分:1)
您可以使用stringByTrimmingCharactersInSet:
的{{1}}方法。
NSSTring
答案 2 :(得分:1)
从字符串的第一个和最后一个中删除逗号(如果有)。
NSString *str1 = @",a,b,c,d,";
NSLog(@"%@",[str1 substringFromIndex:str1.length - 1]);
if ([[str1 substringToIndex:1] isEqualToString:@","])
{
str1 = [str1 substringFromIndex:1];
NSLog(@" == %@",str1);
}
if([[str1 substringFromIndex:str1.length - 1] isEqualToString:@","])
{
str1 = [str1 substringToIndex:str1.length - 1];
NSLog(@"%@",[str1 substringToIndex:str1.length - 1]);
}
答案 3 :(得分:0)
您可以使用字符串操纵器功能。 1.find_last_of 2.find_first_of()
答案 4 :(得分:0)
您可以使用stringByReplacingOccurrencesOfString:withString:options:range:
方法替换','用''。
参考下面的代码,
int strLength = [str1 length];
str1 = [str1 stringByReplacingOccurrencesOfString:@"," withString:@"" options:NSCaseInsensitiveSearch range:NSRangeFromString(@"0,1")];
str1 = [str1 stringByReplacingOccurrencesOfString:@"," withString:@"" options:NSCaseInsensitiveSearch range:NSRangeFromString([NSString stringWithFormat:@"%d,%d",strLength - 1,1])];
答案 5 :(得分:0)
NSString*delete=@"a,b,c,d,";
if ([delete hasPrefix:@","] && [delete hasSuffix:@","])
delete=[ [delete substringFromIndex:1] substringToIndex:delete.length-2];
else if ([delete hasPrefix:@","])
delete= [delete substringFromIndex:1];
else
delete=[delete substringToIndex:delete.length-1];
NSLog(@"delete---%@",delete);