A
A
asha092017-05-09 15:56:12
Java
asha09, 2017-05-09 15:56:12

How to extract a port from a string?

It has its own scanner that takes IP from a string (there may be many of them) and then does what it needs. So, by default there is port 2222, how to extract from a string, for example 0.0.0.0:2223, this same port 2223 in Java?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vitaly Vitrenko, 2017-05-09
@Vestail

String host = "0.0.0.0:2223";
String port = host.substring(host.lastIndexOf(":") + 1);

T
Therapyx, 2017-05-09
@Therapyx

import java.util.StringTokenizer;
String host = "0.0.0.0:2223";
StringTokenizer stringTokenizer = new StringTokenizer(host, ":");
String IP= stringTokenizer.nextElement().toString();
Integer port = Integer.parseInt(stringTokenizer .nextElement().toString());
Output:
Ip = 0.0.0.0 as a string
port = 2223 as int
StringTokenizer is very convenient when the structure of strings is known, you can break it into small tokens according to various criteria, and then simply expand them into the necessary variables. Well, or just skip)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question