格式化IP:端口字符串为

编程入门 行业动态 更新时间:2024-10-23 07:25:25
本文介绍了格式化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:端口字符串为

本文发布于:2023-11-16 17:04:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1606188.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   端口   IP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!