在我的应用程序中,我有一个地址标签,其中包含"address1"、 "Address2"、"City"和"state"的值。在标签中显示时,我需要在每个值之间插入逗号。
但是,如果一个字符串没有值(比如"Address2"),则不应在此处插入唯一的逗号。
谁可以帮我这个事?
这里考虑这dictLocation
是一个包含 Address1、Address2、City、State、Country 和 Zip 的字典:
样品dictLocation
:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"add1", @"Address1", @"add2", @"Address2",@"cityname",@"City",@"state",@"StateName",@" country",@"CountryName",@"350010",@"ZipCode",nil];
代码:
-(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;
}
希望这可以帮助。
如果您需要其他任何东西,请告诉我