Formatting IP:Port string to

前端 未结 6 695
遇见更好的自我
遇见更好的自我 2021-01-23 07:13

I\'m trying to make a little chat program for experimentation, but seeing as I\'m not the best Java programmer, I don\'t know how to separate a port from an IP where they are bo

6条回答
  •  渐次进展
    2021-01-23 08:01

    String s = "127.0.0.1:999";
    String[] parts = s.split(":");
    String address = parts[0];
    int port = Integer.parseInt(parts[1]);
    

    In this case, address will be "127.0.0.1" and port will be the int 999.

    Note that Integer.parseInt will throw a NumberFormatException in this case if the portion of the string after the : cannot be parsed as an integer, as in "127.0.0.1:blahblah". As well, if the string does not contain a : there will be no parts[1].

提交回复
热议问题