substring IP address in java
This program takes string like that 192.168.1.125 and cut every number then开发者_开发问答 converts it to integer, but it returns an error.
import java.lang.String;
import java.lang.Number;
import java.lang.Integer;
class Ip
{
public static void main ( String [] args )
{
int i ;
i = args[0].indexOf ( '.' );
do
{
if ( i != -1 )
args[0].substring ( 0, i );
String str = args[0].substring ( i + 1, args[0].length() );
String str2 = Integer.parseInt ( str );
System.out.println ( str2 );
}
while ( i != -1 );
}
}
Integer.parseInt
returns an integer, not a string (it's entire point is to create an integer):
String str2 = Integer.parseInt ( str );
Note, the compiler gave an error and you should have tried to figure out what it tells you:
Ip.java:16: incompatible types
found : int
required: java.lang.String
String str2 = Integer.parseInt ( str );
On parseInt
parseInt
takes a String
and returns an int
. Here's a simple example of using the method:
int num = Integer.parseInt("42");
System.out.println(num == 42); // prints "true"
API references
int parseInt(String s)
- Parameters:
s
- a String containing the int representation to be parsed - Returns: the integer value represented by the argument in decimal.
- Parameters:
As for your problem, the simplest solution is to use a java.util.Scanner
import java.util.*;
//...
Scanner sc = new Scanner("192.168.1.125").useDelimiter("\\.");
int[] parts = new int[] {
sc.nextInt(), sc.nextInt(), sc.nextInt(), sc.nextInt()
};
System.out.println(Arrays.toString(parts));
// prints "[192, 168, 1, 125]"
The only non-straightforward part of this is the \\.
, which is how you write \.
as a String literal in Java. The reason why you need the \
is because useDelimiter
takes a regex, and in regex dot .
is a metacharacter, so you need to escape it to match a literal dot.
API references
java.util.Scanner
See also
- regular-expressions.info/Dot
- JLS 3.10.6 Escape Sequences for Character and String Literals
You're discarding the result of the first substring, and assigning an integer to a string (as noted by Klatchko). Also, you can simplify if you use a for loop, since IPv4 addresses always have 4 components. This assumes you can't use String.split or similar.
精彩评论