iOS 开发从 Array 生成特定分隔符隔开的 String
从一个String Array 或者 Object Array 生成字符串,使用特定的分隔符隔开,起始和末尾不需要分隔符,当传入的是对象的时候,需要指定Object 中 String 的 key 字符串,效果如下图所示:
直接看代码,只是备忘。
头文件
//
// TGStringTool.h
// DongKe
//
// Created by VanJay on 2018/9/30.
// Copyright © 2018 DongKe. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface TGStringTool : NSObject
+ (NSString *)stringWithStringArr:(NSArray<NSString *> *)arr separatedStr:(NSString *)separatedStr;
+ (NSString *)stringWithArr:(NSArray<id> *)arr valueKey:(NSString *)key separatedStr:(NSString *)separatedStr;
@end
NS_ASSUME_NONNULL_END
实现文件
//
// TGStringTool.m
// DongKe
//
// Created by VanJay on 2018/9/30.
// Copyright © 2018 DongKe. All rights reserved.
//
#import "TGStringTool.h"
@implementation TGStringTool
+ (NSString *)stringWithStringArr:(NSArray<NSString *> *)arr separatedStr:(NSString *)separatedStr {
NSMutableString *temp = [NSMutableString string];
if (arr.count > 0) {
[arr enumerateObjectsUsingBlock:^(NSString *_Nonnull str, NSUInteger idx, BOOL *_Nonnull stop) {
if (str.length > 0) {
[temp appendString:str];
if (idx < arr.count - 1) {
[temp appendString:separatedStr];
}
}
}];
}
return temp;
}
+ (NSString *)stringWithArr:(NSArray<id> *)arr valueKey:(NSString *)key separatedStr:(NSString *)separatedStr {
NSMutableString *temp = [NSMutableString string];
if (arr.count > 0) {
[arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
if ([obj respondsToSelector:NSSelectorFromString(key)]) {
NSString *str = [obj valueForKey:key];
if (str.length > 0) {
[temp appendString:str];
if (idx < arr.count - 1) {
[temp appendString:separatedStr];
}
}
}
}];
}
return temp;
}
@end