Formatting IP:Port string to

前端 未结 6 704
遇见更好的自我
遇见更好的自我 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 07:58

    First, you should check if the String contains a colon. Then, you can use String.split(String) and Integer.parseInt(String) with something like

    String input = "127.0.0.1:8080"; // <-- an example input
    int port = 80; // <-- a default port.
    String host = null;
    if (input.indexOf(':') > -1) { // <-- does it contain ":"?
      String[] arr = input.split(":");
      host = arr[0];
      try {
        port = Integer.parseInt(arr[1]);
      } catch (NumberFormatException e) {
        e.printStackTrace();
      }
    } else {
      host = input;
    }
    System.out.printf("host = %s, port = %d%n", host, port);
    

    Output is

    host = 127.0.0.1, port = 8080
    

提交回复
热议问题