String Split() with special character

Being an Information Systems Management, I have not been really exposed to much nitty gritty details of programming – even on the language that I am exposed to the most – Java. Yes I have done my fair share of debugging and such, but even so I often stumble in some random stuff that waste quite a number of minutes. For example, with String split() method that I was worked with.

As you might have known (or not), String has he String class has a split() method that will break a string based on a certain expression and return a String array.

public class StringSplitBasic {
public static void main(String args[]) throws Exception{
String testString = “This-is-a-basic-example”;
System.out.println(
java.util.Arrays.toString(
testString.split(“-”)
));

// the output is an array of [This, is , a, basic, example]
}
}

Simple enough. However, not so when I am using special character such as ‘.’ (dot) or ‘|’ (pipe).

public class FailedStringSplitNotSoBasic {
public static void main(String args[]) throws Exception{
String testString = “This|line|uses|pipes”;

System.out.println(java.util.Arrays.toString(
testString.split(“|”)
));
// output : [,T,h,i,s,|,l,i,n,e,|u,s,e,s,|,p,i,p,e,s]
}
}

quite lame heh. Apparently, the special character like ‘l’ needs to be escaped with a ‘\’. However, since ‘\’ is also a special character in Java (again), I need to escape it again with another ‘\’. Ok I am stupid.

So my to do for later is to find out the list of Java’s special characters.

Related posts:

  1. How to get current date time in String
  2. Create Dummy Progress Dialog in Android
  3. How to do redirect to an external dynamic site in Struts2
  4. Declare Global Variable In Android via android.app.Application
  5. Using java.util.Set interface

Leave a Reply