0

I'm getting this ips from my server like:

"/177.127.101.68:53964"
"/201.80.15.100:54263"
"/177.67.38.54:51309"

and i need it to be like just "177.127.101.68", i was going to delete the last 5 string characters but sometimes it comes "/186.213.186.40:4625" so i dont know exactly how to do it... is there any way to do that?

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
Thiago Sabin
  • 137
  • 1
  • 12

3 Answers3

5

Use the split() and substring() methods of the String class, for one approach:

String ip = "/177.127.101.68:53964";
String whatYouWant = ip.split(":")[0].substring(1);

Please see the Javadocs for split and substring. You'll find yourself using them a lot, in my opinion.

Kon
  • 10,702
  • 6
  • 41
  • 58
  • If there is no ":" i ll get an error or nothing ll happen? – Thiago Sabin Jan 21 '15 at 15:36
  • If there is no ":", the resulting array will be of size 1 (will have exactly 1 element, containing the whole line). So it will still function. – Amr Jan 21 '15 at 15:40
  • @ThiagoSabin test it (it should work fine). Also all your examples contain `:` so if there is possibility that there will be no `:` you should mention about this in your question. Stack Overflow is not some contest site where answerers should focus of all possible corner cases, so it is in best interest of asker to put as many important informations as possible. – Pshemo Jan 21 '15 at 15:40
2

You only need substring:

String ip = "/177.127.101.68:53964";
String result = ip.substring(1, ip.indexOf(':')-1);
Jens
  • 67,715
  • 15
  • 98
  • 113
2

Other way around could be something like

String myIP = "/177.127.101.68:53964";
URL url = new URL("http:/" + myIP);// will create URL for http://177.127.101.68:53964
String host = url.getHost(); // will return only 177.127.101.68 part
Pshemo
  • 122,468
  • 25
  • 185
  • 269