在我的应用程序中,我有一个地址标签,其中包含“address1”,“Address2”,的值城市“和”状态“。我需要在标签中显示时在每个值之间插入逗号。
但如果一个字符串没有值(例如“Address2”),则不应在那里插入唯一的逗号。
有人可以帮我吗?
答案 0 :(得分:1)
这里考虑dictLocation
是一个包含Address1,Address2,City,State,Country和Zip的字典:
示例dictLocation
:
NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:@“add1”,@“Address1”,@“add2”, @ “地址2”,@ “城市名”,@ “市”,@ “状态”,@ “Statename的”,@ “国家”,@ “国家或地区名称”,@ “350010”,@ “邮编”,零];
代码:
-(NSMutableString *)createLocationAddress:(NSDictionary *)dictLocation
{
NSMutableString *strAddress = [[NSMutableString alloc] initWithString:@""];
NSString *strStreetAddress1 = @"";
if(dictLocation != nil && [dictLocation valueForKey:@"Address1"] != nil)
{
strStreetAddress1 = [StringUtility trimWhiteSpaceAndNewLine:[dictLocation valueForKey:@"Address1"]];
}
[strAddress appendString:strStreetAddress1];
NSString *strAddress2 = @"";
if(dictLocation != nil && [dictLocation valueForKey:@"Address2"] != nil)
{
strAddress2 = [StringUtility trimWhiteSpaceAndNewLine:[dictLocation valueForKey:@"Address2"]];
}
if(![strAddress2 isEqualToString:@""])
{
if(![strAddress isEqualToString:@""])
[strAddress appendString:@", "];
[strAddress appendString:strAddress2];
}
NSString *strLocationCity = @"";
if(dictLocation != nil && [dictLocation valueForKey:@"City"] != nil)
{
strLocationCity = [StringUtility trimWhiteSpaceAndNewLine:[dictLocation valueForKey:@"City"]];
}
if(![strLocationCity isEqualToString:@""])
{
if(![strAddress isEqualToString:@""])
[strAddress appendString:@", "];
[strAddress appendString:strLocationCity];
}
NSString *strLocationState = @"";
if(dictLocation != nil && [dictLocation valueForKey:@"StateName"] != nil)
{
strLocationState = [StringUtility trimWhiteSpaceAndNewLine:[dictLocation valueForKey:@"StateName"]];
}
if(![strLocationState isEqualToString:@""])
{
if(![strAddress isEqualToString:@""])
[strAddress appendString:@",\n"];
[strAddress appendString:strLocationState];
}
NSString *strLocationCountry = @"";
if(dictLocation != nil && [dictLocation valueForKey:@"CountryName"] !=nil)
{
strLocationCountry = [StringUtility trimWhiteSpaceAndNewLine:[dictLocation valueForKey:@"CountryName"]];
}
if(![strLocationCountry isEqualToString:@""])
{
if(![strAddress isEqualToString:@""])
[strAddress appendString:@", "];
[strAddress appendString:strLocationCountry];
}
NSString *strLocationZipcode = @"";
if(dictLocation != nil && [dictLocation valueForKey:@"ZipCode"] != nil)
{
strLocationZipcode = [StringUtility trimWhiteSpaceAndNewLine:[dictLocation valueForKey:@"ZipCode"]];
}
if(![strLocationZipcode isEqualToString:@""])
{
if(![strAddress isEqualToString:@""])
[strAddress appendString:@", "];
[strAddress appendString:strLocationZipcode];
}
return strAddress;
}
希望这有帮助。
如果您还有其他需要,请告诉我