Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string in Java?

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 Answers

You can use String.split.

String   test = "a|b|c";
String[] splitStr = test.split("\\|"); // {"a", "b", "c"}
like image 59
Propeng Avatar answered Jun 26 '26 00:06

Propeng


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

like image 33
OscarRyz Avatar answered Jun 26 '26 00:06

OscarRyz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!