如果变量不是 nil,我想从变量中连接一些字符串。 如果它们为零,我不想包括它们。 以下代码有效,但很笨拙,并且随着其他变量的增加而按比例变得更加复杂。谁能推荐一种更优雅的方式来做到这一点?
NSString *city = self.address.city== nil ? @"" : self.address.city;
NSString *state = self.address.state== nil ? @"" : self.address.state;
NSString *zip = self.address.zip== nil ? @"" : self.address.zip;
NSString *bestCity;
if (city.length>0&&state.length>0&&zip.length>0) {
bestCity = [NSString stringWithFormat: @"%@ %@ %@", city, state,zip];
}
else if (city.length>0&&state.length>0) {
bestName = [NSString stringWithFormat: @"%@ %@", city,state];
}
else if (city.length>0&&zip.length>0) {
bestCity = [NSString stringWithFormat: @"%@ %@", city,zip];
}
else if (city.length>0&&zip.length>0) {
bestCity = [NSString stringWithFormat: @"%@ %@", city,zip];
}
else if (city.length>0) {
bestCity = [NSString stringWithFormat: @"%@", city];
}
else if (state.length>0) {
bestCity = [NSString stringWithFormat: @"%@", state];
}
else if (zip.length>0) {
bestCity = [NSString stringWithFormat: @"%@", zip];
}
else {
bestCity = @"";
}
我通常会做这样的事情:
NSMutableArray *bestCityArr = [@[] mutableCopy]; // [[NSMutableArray alloc] init];
if (city.length > 0)
[bestCityArr addObject:city];
if (state.length > 0)
[bestCityArr addObject:state];
if (zip.length > 0)
[bestCityArr addObject:zip];
NSString *bestCity = [bestCityArr componentsJoinedByString:@" "];
NSMutableArray *items = [[NSMutableArray alloc] init];
if (self.address.city)
[items appendObject:self.address.city];
if (self.address.state)
[items appendObject:self.address.state];
if (self.address.zip)
[items appendObject:self.address.zip];
NSString *bestCity = [items componentsJoinedByString:@" "];
这段代码可能会对你有所帮助!
- (NSString *)concatenateString
{
NSMutableString *bestCity = [NSMutableString string];
NSString *city = self.address.city ?: @"";
[bestCity appendString:city];
NSString *state = self.address.state ?: @"";
if (state.length > 0) {
[bestCity appendString:@" "];
}
[bestCity appendString:state]];
NSString *zip = self.address.zip ?: @"";
if (zip.length > 0) {
[bestCity appendString:@" "];
}
[bestCity appendString:zip];
return bestCity.length > 0 ? bestCity : @"";
}