permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why the output is different from usual String.split() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why the output is different from usual String.split()" Watch "why the output is different from usual String.split()" New topic
Author

why the output is different from usual String.split()

charan sri
Greenhorn

Joined: Sep 14, 2005
Posts: 22
import java.lang.*;
class StringSplit
{
public static void main(String[] args)
{
String str="sss|sss|ssssss|sssds|sssss";
String[] a= str.split("/|");
for(int i=0;i<a.length;i++)
{
System.out.println(i+"-->"+a[i]);
}
}
}
Can any one explain me why the above code is behaving differently?
If i give ',' in place of '|' the output is correct.
I dont undersatand why?

Thanks
Charan.
charan sri
Greenhorn

Joined: Sep 14, 2005
Posts: 22
Administrators or moderators plz delete my previous topic.

Thanks,
Charan.
Todd Johnson
Ranch Hand

Joined: Sep 03, 2005
Posts: 61
I'm not completely up to speed on regular expressions, but I believe the pipe (|) has the special meaning "OR" in a regular expression. So the following code...

String[] a = str.split("|");

Really doesn't make sense (it matches everything I'm guessing). So if we want to look for the literal character pipe (|) we need to escape it out like this...

String[] a = str.split("\\|");

This will give you the behaviour you are looking for.
Akshay Kiran
Ranch Hand

Joined: Aug 18, 2005
Posts: 220
exactly, you need to escape it twice because '|' is a Metacharacter while ',' is not and doesn't need to be escaped.
Also note however this intricacy

String s= "\\|";

does the same work as
String s= arg[0]
and arg[0]= "\|" at the command line or from a file.


"It's not enough that we do our best; sometimes we have to do<br />what's required."<br /> <br />-- Sir Winston Churchill
charan sri
Greenhorn

Joined: Sep 14, 2005
Posts: 22
Thanks akshay and Johnson

Thanks,
Charan.
 
 
subject: why the output is different from usual String.split()
 
Similar Threads
java primitive problem
Object creation
unicode escapes
problem with string array
String splitting