Are you looking to get a string whose value is "192.168.3" Or are you looking to get numerical values for each of the individual IP address octets?
Originally Posted by sxlend
If it's the first one:
Suppose you have a String whose value is, say, "192.168.16.122"
String ipString = "192.168.16.122";
- Use the String lastIndexOf() method to find the index of the last '.' character in ipString.
- Use the String substring() method to create a new string that has everything from the beginning of ipString to the index position you just found.
On the other hand, if you need to get the numerical values into int variables:
- Use the String split() method to create an array of strings, each of whose value is one of the pieces of the IP Address String:
Now, splitting on the special character class '.' requires some regular-expression syntax that might not be exactly obvious to some of us, but it goes like this:
String  octetStrings = ipString.split("\\.");
(For purposes of debugging, make a loop that prints out the elements of ipStrings here.)
- Each of the strings in the array can be parsed to obtain its integer value. You can create an array of ints (same size as the octetStrings array) and parse all of them in a loop.
Or you can parse whichever ones you want as separate ints:
For example to get the first one:
int i0 = Integer.parseInt(octetStrings);