1

I have ip address example "27.96.168.92" and would like to reorder the each Octates in the ip address. so the output should be "92.168.96.27".

I can achieve this with string split functionality. Is there any way to achieve this without split functionality of java string, something like load it to char array and then loop ?

Actual ip : "27.96.168.92" expected ip : "92.168.96.27"

Guru
  • 29
  • 8

1 Answers1

1

I would use a simple regular expression:

String ip = "27.96.168.92";
String switched = ip.replaceAll("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)", "$4.$3.$2.$1");
System.out.println(switched);

Output:

92.168.96.27

Because you're only switching numbers around, you shouldn't require a regex pattern that conforms to a valid IP address.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116