2017-09-19 4 views
-1

私はLAN IPを提供するプログラムを持っているので、IPの最後のオクテットを変更する必要があります。最初の3つは同じままですLAN IPテキストフィールドに入力された内容に基づいています。文字列として入力されたIPアドレスを修正するJavaの方法

例: ユーザーは192.168.1.97をLAN IPとして入力します最後のオクテット "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") 
関連する問題