我正在使用一个功能来添加。在字符串中的每三个字符之后。但是如何在数字前删除“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?
答案 0 :(得分:2)
我建议:
NSString *ipAddress = @"010.000.001.016";
将字符串拆分为子字符串数组:
NSArray *ipAddressComponents = [myString componentsSeparatedByString:@"."];
使用for循环运行数组,并将转换分别运行到int表示:
for(int i = 0; i < ipAddressComponents.count;i++)
{
[ipAddressComponents objectAtIndex:i] = [NSString stringWithFormat:@"%d",[[ipAddressComponents objectAtIndex:i]intValue]];
}
将数组重新加入字符串
NSString *newIpAddress = [ipAddressComponents componentsJoinedByString:@"."];
这应该导致获得IP地址:10.0.1.16
答案 1 :(得分:0)
您可以使用字符串函数,并在componentsSeparatedByString
和componentsJoinedByString
函数的帮助下获得预期的输出。
使用以下方法:
-(NSString*)removeZeroPrefix:(NSString*)aStrIP{
NSMutableArray *subStringArray = [[NSMutableArray alloc] init];
NSArray *arrayOfSubString = [aStrIP componentsSeparatedByString:@"."];
for (NSString *aSingleString in arrayOfSubString)
{
[subStringArray addObject:[NSNumber numberWithInteger:[aSingleString integerValue]]];
}
return [subStringArray componentsJoinedByString:@"."];
}
用法:
[self removeZeroPrefix:@"010.000.001.016"];
[self removeZeroPrefix:@"192.168.001.001"];
输出
Printing description of aStrIP:
10.0.1.16
Printing description of aStrIP:
192.168.1.1
希望这会有所帮助!
答案 2 :(得分:0)
在Swift中
let ip = "0125.052.000.10"
let split = ip.components(separatedBy: ".")
for number in split {
if let isNumber = Int(number){
print(isNumber) // add this isNumber into array which is shows without initial zeros.
}
}
最后将创建的数组作为String加入点组件