2017-09-19 9 views
-1

LAN IP를 제공하는 프로그램이 있는데, 그 다음에 IP의 마지막 옥텟을 수정할 수 있어야합니다. 첫 번째 3은 동일하게 유지됩니다 LAN IP 텍스트 필드에 입력 된 내용을 기반으로합니다.Java 문자열을 입력 한 IP 주소를 수정하는 방법

예 : 사용자가 LAN IP로 192.168.1.97을 입력합니다. 마지막 옥텟 "97"을 조작 할 수 있어야합니다. 그렇게하면 다른 변수 나 문자열을 가질 수 있습니다. 192.168.1.100 또는 내가 마지막 옥텟에 설정하고자하는 다른 것. 100에 마지막 옥텟을 설정하려면

답변

0
String ip = "192.168.1.97"; 

// cut the last octet from ip (if you want to keep the . at the end, add 1 to the second parameter 
String firstThreeOctets = ip.substring(0, ip.lastIndexOf(".")); // 192.168.1 

String lastOctet = ip.substring(ip.lastIndexOf(".") + 1); // 97 

다음, 단순히 수행

String newIp = firstThreeOctet + ".100"; // 192.168.1.100 
0

당신의 끝에 숫자를 교체 이러한 방법

public static byte getLastOctet(String ip) { 
    String octet = ip.substring (ip.lastIndexOf('.') + 1); 
    return Byte.parseByte(octet); 
} 

public static String setLastOctet(String ip, byte octet) { 
    return ip.substring(0, ip.lastIndexOf ('.') + 1) + octet; 
} 
0

을 사용할 수 있습니다 입력.

String ipAddress = "192.168.1.97"; 
String newIpAddress = ipAddress.replaceFirst("\\d+$", "100")