格式化IP:端口字符串为 [英] Formatting IP:Port string to

查看:156
本文介绍了格式化IP:端口字符串为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个用于实验的小聊天程序,但看到我不是最好的Java程序员,我不知道如何将端口与IP分开,它们都在同一个字符串中。

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 both in the same string.

这不是很清楚,但这基本上就是我想要做的。
用户在IP中输入IP和端口:端口格式
扫描器抓取它并将其放入字符串
不知何故将冒号前的所有内容放入字符串中,并将冒号后的所有数字放入int中。

This isn't super clear, but here's basically what I want to do. User enters IP and port in IP:Port format Scanner grabs it and puts it into a String Somehow put everything before the colon into a string and all numbers after the colon into an int.

关于如何做到这一点的任何想法?

Any ideas on how to do this?

推荐答案

首先,你应该检查 String 是否包含冒号。然后,你可以使用 String.split(String) Integer.parseInt(String) ,其中包含

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);

输出

host = 127.0.0.1, port = 8080

这篇关于格式化IP:端口字符串为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆