2

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.

8 Answers 8

8

You can use String.split.

String   test = "a|b|c";
String[] splitStr = test.split("\\|"); // {"a", "b", "c"}
4
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

3

I would try the String.split method, personally.

2

Yes, there's something similar.

String[] words = thing.split("|"); 
2
  • 1
    Expect that it takes a regex string, not a char.
    – BalusC
    May 25, 2010 at 17:52
  • True. I just checked in the java.util.regex.Pattern class. It doesn't appear to me that the | character has to be escaped. May 25, 2010 at 17:58
1

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

String s = "172.16.1.100";

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

0

Exactly the same : String.split

0

Use String.split().

0

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

2
  • No, \\. \ is a string escape character.
    – Propeng
    May 25, 2010 at 18:05
  • apologies, I didn't realize the stackoverflow software would escape backslashes. my original post had double backslashes, you are of course correct. May 25, 2010 at 18:17

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.