3

I have a string like |serialNo|checkDelta?|checkFuture?|checkThis?|.

Now I am using the following code to split the string.

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

but when I use this I get array of string that contains each and every character, whereas I need string which contains letter like serialNo, checkDelta?, checkFuture?, checkthis?.

How to get these? Am I missing something?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
M.J.
  • 16,266
  • 28
  • 75
  • 97

3 Answers3

16

You'll have to escape your pipe character (split takes a regular expression as argument and therefore "|" is a control character):

str.split("\\|");

Please note: the resulting array contains an empty string at the beginning since you have "|" at start of your string.

Howard
  • 38,639
  • 9
  • 64
  • 83
  • +1 for the note good thing to metion – RMT Jul 13 '11 at 17:12
  • An alternative syntax for an equivalent regular expression is: `"[|]"` -- the pipe loses it's meaning in a character class. –  Jul 13 '11 at 17:42
3

You are using a special character and will have to escape it: str.split("\\|");

avivas
  • 173
  • 1
  • 3
  • 17
0

Use StringTokenizer..

String str="|serialNo|checkDelta?|checkFuture?|checkThis?|"
StringTokenizer st=new StringTokenizer(str,"|",false);
String s1 = st.nextToken();
String s2 = st.nextToken();
String s3 = st.nextToken();
String s4 = st.nextToken();

s1=serialNo

s2=checkDelta?

s3=checkFuture?

s4=checkThis?

Refer to javadocs for reading about StringTokenizer

http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html

Sumit
  • 736
  • 8
  • 26