views:

231

answers:

8

Imagine I have this string:

string thing = "sergio|tapia|gutierrez|21|Boston";

In C# I could go:

string[] Words = thing.Split('|');

Is there something similar in Java? I could use Substring and indexOf methods but it is horribly convoluted. I don't want that.

+2  A: 

I would try the String.split method, personally.

Matt
+1  A: 

Yes, there's something similar.

String[] words = thing.split("|"); 
Gilbert Le Blanc
Expect that it takes a regex string, not a char.
BalusC
So the above code wouldn't work?
Serg
True. I just checked in the java.util.regex.Pattern class. It doesn't appear to me that the | character has to be escaped.
Gilbert Le Blanc
A: 

Exactly the same : String.split

mexique1
A: 

Use String.split().

zipcodeman
+8  A: 

You can use String.split.

String   test = "a|b|c";
String[] splitStr = test.split("\\|"); // {"a", "b", "c"}
Propeng
+1  A: 

It's easy. You just call the split method with a delimiter

String s = "172.16.1.100";

String parts[] = s.split("\\.");

Guy
A: 

you need to escape the pipe delimiter with \\, someString.split("\\|");

Paul Sanwald
No, \\. \ is a string escape character.
Propeng
apologies, I didn't realize the stackoverflow software would escape backslashes. my original post had double backslashes, you are of course correct.
Paul Sanwald
+4  A: 
String thing = "sergio|tapia|gutierrez|21|Boston";
String[] words = thing.split("\\|");

The problem with "|" alone, is that, the split method takes a regular expression instead of a single character, and the | is a regex character which hava to be scaped with \

But as you see it is almost identical

OscarRyz