用"/"拼接三個字符串,字符串爲空則不拼接,有下邊兩種實現方式bash
if else
的實現方式+ (NSString *)getGoodsRuleWithCarLength:(NSString *)carLength andCarType:(NSString *)carType andSpecialRequire:(NSString *)specialRequire andEntrance:(TYTGoodsRuleEntrance)entrance{
NSString *goodsRule = nil;
if(carLength.length > 0){
if(carType.length > 0){
if(specialRequire.length > 0){
goodsRule = [NSString stringWithFormat:@"%@/%@/%@",carLength,carType,specialRequire];
}else{
goodsRule = [NSString stringWithFormat:@"%@/%@",carLength,carType];
}
}else{
if(specialRequire.length > 0){
goodsRule = [NSString stringWithFormat:@"%@/%@",carLength,specialRequire];
}else{
goodsRule = [NSString stringWithFormat:@"%@",carLength];
}
}
}else{
if(carType.length > 0){
if(specialRequire.length > 0){
goodsRule = [NSString stringWithFormat:@"%@/%@",carType,specialRequire];
}else{
goodsRule = [NSString stringWithFormat:@"%@",carType];
}
}else{
if(specialRequire.length > 0){
goodsRule = [NSString stringWithFormat:@"%@",specialRequire];
}else{
goodsRule = @"";
}
}
}
return goodsRule;
}
複製代碼
//建立NSString的分類
/**
* 用斜線拼接參數
* count爲參數個數,其它參數必須是NSString類型(可爲nil)
* eg.須要拼接三個字符串 長、寬、高爲 "長/寬/高" 方法調用方式爲[NSString splicWithSlantParamsCount:3, @"長", @"寬", @"高"];
*/
+ (NSString *)stringSplicWithSlantParamsCount:(int)count,...{
if(count < 1){
return @"";
}
int index = 0;
va_list args;
va_start(args, count);
//拼接後的字符串
NSString *paramSum = @"";
NSString *otherParam;
//循環到結尾就中止循環
while(index<count){
index ++;
otherParam = va_arg(args, NSString *);
if(paramSum.length > 0){
if(otherParam.length > 0){
paramSum = [NSString stringWithFormat:@"%@/%@",paramSum,otherParam];
}
}else{
if(otherParam.length > 0){
paramSum = otherParam;
}
}
}
va_end(args);
return paramSum;
}
複製代碼
+ (NSString *)getGoodsRuleWithCarLength:(NSString *)carLength andCarType:(NSString *)carType andSpecialRequire:(NSString *)specialRequire andEntrance:(TYTGoodsRuleEntrance)entrance{
//用"/"拼接字符串
NSString *goodsRule = [NSString stringSplicWithSlantParamsCount:3, carLength, carType, specialRequire];
return goodsRule;
}
複製代碼
也曾考慮過在封裝的代碼中經過vsnprintf
計算可變參數的長度,可是參數有可能爲空,就會致使崩潰,因此最後決定直接傳進來參數的個數ui