-1

我想知道在Java中将字符串“00155D038D01”转换为macAdress格式的最简单方法。

4

5 回答 5

12

尝试使用正则表达式

char divisionChar = ':';//change to '-' if you want your mac to be like 00-15-5D-03-8D-01
String unformattedMAC = "00155D038D01";
String formattedMAC = unformattedMAC.replaceAll("(.{2})", "$1"+divisionChar).substring(0,17);

适用于您拥有的所有 MAC 地址

于 2013-01-28T10:32:43.223 回答
8

我会说这"00155D038D01".replaceAll("(..)(?!$)", "$1-")是最简单的:)

于 2013-01-28T10:34:31.307 回答
7

明显地,

public String convertToMacAddress(String input) {
   if (input.equals("00155D038D01") {
       return "00-15-5D-03-8D-01";
   } 

   return null; 
}
于 2013-01-28T10:26:44.847 回答
1
String address = "00155D038D01";
StringBuilder sb = new StringBuilder(address);

for(int i = 2; i < address.length()+(i/3); i+=3){
   sb.insert(i, ':');
}

System.out.println(sb.toString());
于 2013-01-28T10:36:54.920 回答
1

直截了当的方法:

String s = "00155D038D01";
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length();)
{
    sb.append(s.substring(i++, ++i));
    if(i < s.length()) sb.append("-");
}
String mac = sb.toString();
于 2013-01-28T10:32:45.603 回答