Xylo_matic
Xylo_matic

Reputation: 163

Splitting string gives null result in java

i am trying very simple splitting. I dont know why it is not working.

String abc= "192.168.120.2";
String[] eachByteabc= abc.split("."); 

When I debug it and see, I get the result that abc contains : 192.168.120.2. But when I do split, it does not give me error but gives me null result. I think, i have made some silly mistake. Can you tell me where I am wrong. What should I do. Thank you in advance.

Upvotes: 3

Views: 131

Answers (5)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

You need to escape the ., since it's a regex operator. Change it to:

String[] eachByteabc= abc.split("[.]"); 

Addition, thanks to @sparks:

While this will work, the [] characters in regex are used to annotate a set, so if you are looking for where it might be in a limited series of characters, you should use them.

In this case - use \\. to escape the . character.

Upvotes: 3

sparks
sparks

Reputation: 764

String.split uses regex, so you need to use abc.split("\\.");

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29

Upvotes: 0

RZMars
RZMars

Reputation: 125

String[] eachByteabc = abc.split("."); is not eorr,but you can not to debug and Watch the values.use String[] eachByteabc = abc.split(".");you can Watch values in the debug.

Upvotes: 1

Sergey Morozov
Sergey Morozov

Reputation: 4608

Try it =):

String[] eachByteabc= abc.split("\\.");

Upvotes: 3

cangrejo
cangrejo

Reputation: 2202

public String[] split(String regex) takes a regular expression as an argument. You must escape the point, since it's a regex operator.

Upvotes: 2

Related Questions