【发布时间】:2017-06-08 12:35:42
【问题描述】:
我正在使用一个函数来添加 .在字符串中每三个字符之后。但是如何删除数字前面的“0”。
-(NSString *)formatStringAsIpAddress:(NSString*)MacAddressWithoutColon
{
NSMutableString *macAddressWithColon = [NSMutableString new];
for (NSUInteger i = 0; i < [MacAddressWithoutColon length]; i++)
{
if (i > 0 && i % 3 == 0)
[macAddressWithColon appendString:@"."];
unichar c = [MacAddressWithoutColon characterAtIndex:i];
[macAddressWithColon appendString:[[NSString alloc] initWithCharacters:&c length:1]];
}
return macAddressWithColon;
}
如果我有 IP 地址 010.000.001.016 我怎样才能像 10.0.1.16 一样设置它?如果我有 IP 地址 192.168.001.001?如何从IP地址中删除前0?
【问题讨论】:
-
不是更漂亮的方式,但是:
NSMutableArray *numberComponents = [[NSMutableArray alloc] init]; for (NSString *aSubString in [str componentsSeparatedByString:@"."]) { [numberComponents addObject:@([aSubString integerValue])]; } NSString *final = [numberComponents componentsJoinedByString:@"."];可以解决问题 -
不就是把整个字符串地址用句点分割成一个Int数组吗?
-
正如@El Tomato 所说 - 将字符串拆分为三个字符的块,将它们转换为 Int,并从中创建没有前导零的字符串
标签: ios objective-c nsstring