Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by char in java

I'm getting a string from the web looking like this:

Latest Episode@04x22^Killing Your Number^May/15/2009

Then I need to store 04x22, Killing Your Number and May/15/2009 in diffent variables, but it won't work.

String[] all = inputLine.split("@");
String[] need = all[1].split("^");
show.setNextNr(need[0]);
show.setNextTitle(need[1]);
show.setNextDate(need[2]);

Now it only stores NextNr, with the whole string

04x22^Killing Your Number^May/15/2009

What is wrong?

like image 555
Casper Avatar asked Mar 14 '11 08:03

Casper


People also ask

Can you split a string into characters Java?

Using the String#split Method The String class comes with a handy method called split. As the name implies, it splits a string into multiple parts based on a given delimiter or regular expression.

How do you split a string at a certain character?

To split a string with specific character as delimiter in Java, call split() method on the string object, and pass the specific character as argument to the split() method. The method returns a String Array with the splits as elements in the array.


2 Answers

String.split(String regex)

The argument is a regualr expression, and ^ has a special meaning there; "anchor to beginning"

You need to do:

String[] need = all[1].split("\\^");

By escaping the ^ you're saying "I mean the character '^' "

like image 181
Brian Roach Avatar answered Oct 17 '22 05:10

Brian Roach


If you have a separator but you don't know if it contains special characters you can use the following approach

String[] parts = Pattern.compile(separator, Pattern.LITERAL).split(text);
like image 22
Peter Lawrey Avatar answered Oct 17 '22 05:10

Peter Lawrey