2

If I have a IP address String like : 10.120.230.78 I would like to get 10.120. out of it

But the parts of the address can change from 1 tot 3 numbers as we all know ...

1.1.1.1 to 255.255.255.255 so ....

I believe you can use a pattern, but I don't have an idea how to.

4 Answers 4

12

assume you store your ip as a string called ip, you can use String.split() to get an array of the parts:

String[] tokens = ip.split("\\.");
Sign up to request clarification or add additional context in comments.

Comments

2
ip.substring(0, ip.indexOf('.',ip.indexOf('.') + 1) + 1)

where ip is the string holding the IP address.

Comments

1
  1. The best way is String.split() as already mentioned by amit. E.g.

    String[] ipAddressParts = ipAddress.split();
    
  2. Also you can use

    StringTokenizer stringTokenizer = new StringTokenizer( ipAddress, "." );
    while ( stringTokenizer.hasMoreTokens() )  {
      System.out.println( stringTokenizer.nextToken() );
    }
    
  3. java.util.Scanner

Comments

0

Take a look at String.split() it's equivalent to php's explode()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.