从NSString动态附加和删除子字符串

时间:2012-06-13 06:32:10

标签: objective-c ios xcode nsstring substring

我动态追加并从NSString中删除子串 -

在我执行的具体操作中(我在添加新字符串时使用逗号分隔符) -

self.selectedString = [self.selectedString length] < 1 ? newSelectedString 
                                                       : [self.selectedString stringByAppendingFormat:@",%@",newSelectedString];

删除 - 现在这个逗号在删除字符串时为我创建了问题。 目前我正在使用这个解决方案 -

self.selectedString = [self.selectedString stringByReplacingOccurrencesOfString:newSelectedString
                                                                     withString:@""];

NSRange rangeSingleComma = [self.selectedString rangeOfString:@","];
NSRange rangeDoubleComma = [self.selectedString rangeOfString:@",,"];
if (rangeSingleComma.location == [self.selectedString length] - 1) {
    self.selectedString = [self.selectedString substringToIndex:[self.selectedString length] - 1];
}
if (rangeSingleComma.location == 0) {
    self.selectedString = [self.selectedString substringFromIndex:1];
}
if (rangeDoubleComma.location != NSNotFound) {
    self.selectedString = [self.selectedString stringByReplacingOccurrencesOfString:@",,"
                                                                         withString:@","];
 }

但这是一种非常肮脏的方法,任何人都可以提出一个很好的方法。

2 个答案:

答案 0 :(得分:5)

你可以做这样的事情

NSString *str = @"aaa,bbb,ccc";
NSMutableArray *arr = [[str componentsSeparatedByString:@","] mutableCopy];

int indexToRemove = -1;
for (int i = 0; i < arr.count; i++) {
    NSString *string = [arr objectAtIndex:i];
    if([string isEqualToString:@"aaa"])
    {
        indexToRemove = i;
        break;
    }
}

if(indexToRemove != -1)
{
    [arr removeObjectAtIndex:indexToRemove];
}

NSString *newString = [arr componentsJoinedByString:@","];

答案 1 :(得分:2)

您是否需要将此逗号分隔列表存储为字符串?相反,尝试维护NSString的NSArray / NSMutableArray。这使得随意添加或删除任何项目变得容易。当您需要数组的逗号分隔字符串表示时,只需执行:

 [self.selectedArray componentsJoinedByString:@","]

如果您仍想使用self.selectedString属性,只需将以上代码行放入getter方法:

 - (NSString *) selectedString {
      return [self.selectedArray componentsJoinedByString:@","]
 }