在Objective-C中,从数组中的字符串中删除空格可以使用以下方法:
stringByReplacingOccurrencesOfString:withString:
方法NSString *stringWithSpaces = @"Hello World";
NSString *stringWithoutSpaces = [stringWithSpaces stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"%@", stringWithoutSpaces); // 输出:HelloWorld
componentsSeparatedByCharactersInSet:
方法和componentsJoinedByString:
方法NSString *stringWithSpaces = @"Hello World";
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
NSArray *components = [stringWithSpaces componentsSeparatedByCharactersInSet:whitespaceSet];
NSString *stringWithoutSpaces = [components componentsJoinedByString:@""];
NSLog(@"%@", stringWithoutSpaces); // 输出:HelloWorld
stringByReplacingOccurrencesOfString:withString:options:range:
方法NSString *stringWithSpaces = @"Hello World";
NSRange range = NSMakeRange(0, stringWithSpaces.length);
NSString *stringWithoutSpaces = [stringWithSpaces stringByReplacingOccurrencesOfString:@" " withString:@"" options:0 range:range];
NSLog(@"%@", stringWithoutSpaces); // 输出:HelloWorld
在数组中应用这些方法,可以使用enumerateObjectsUsingBlock:
方法遍历数组中的每个字符串,并使用上述方法删除空格。
NSArray *stringsWithSpaces = @[@"Hello World", @"Another String"];
NSMutableArray *stringsWithoutSpaces = [NSMutableArray arrayWithCapacity:stringsWithSpaces.count];
[stringsWithSpaces enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *stringWithSpaces = (NSString *)obj;
NSString *stringWithoutSpaces = [stringWithSpaces stringByReplacingOccurrencesOfString:@" " withString:@""];
[stringsWithoutSpaces addObject:stringWithoutSpaces];
}];
NSLog(@"%@", stringsWithoutSpaces); // 输出:(HelloWorld, AnotherString)
这些方法可以用于删除字符串中的空格,并且可以在数组中应用这些方法以删除所有字符串中的空格。
领取专属 10元无门槛券
手把手带您无忧上云