首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Objective-C从数组中的字符串中删除空格

在Objective-C中,从数组中的字符串中删除空格可以使用以下方法:

  1. 使用stringByReplacingOccurrencesOfString:withString:方法
代码语言:objective-c
复制
NSString *stringWithSpaces = @"Hello World";
NSString *stringWithoutSpaces = [stringWithSpaces stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"%@", stringWithoutSpaces); // 输出:HelloWorld
  1. 使用componentsSeparatedByCharactersInSet:方法和componentsJoinedByString:方法
代码语言:objective-c
复制
NSString *stringWithSpaces = @"Hello World";
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
NSArray *components = [stringWithSpaces componentsSeparatedByCharactersInSet:whitespaceSet];
NSString *stringWithoutSpaces = [components componentsJoinedByString:@""];
NSLog(@"%@", stringWithoutSpaces); // 输出:HelloWorld
  1. 使用stringByReplacingOccurrencesOfString:withString:options:range:方法
代码语言:objective-c
复制
NSString *stringWithSpaces = @"Hello World";
NSRange range = NSMakeRange(0, stringWithSpaces.length);
NSString *stringWithoutSpaces = [stringWithSpaces stringByReplacingOccurrencesOfString:@" " withString:@"" options:0 range:range];
NSLog(@"%@", stringWithoutSpaces); // 输出:HelloWorld

在数组中应用这些方法,可以使用enumerateObjectsUsingBlock:方法遍历数组中的每个字符串,并使用上述方法删除空格。

代码语言:objective-c
复制
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)

这些方法可以用于删除字符串中的空格,并且可以在数组中应用这些方法以删除所有字符串中的空格。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券