Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a string in java on more than one symbol

I want to split a string when following of the symbols encounter "+,-,*,/,=" I am using split function but this function can take only one argument.Moreover it is not working on "+". I am using following code:-

Stringname.split("Symbol");

Thanks.

like image 304
Saumyaraj Avatar asked Aug 05 '13 14:08

Saumyaraj


1 Answers

String.split takes a regular expression as argument.

This means you can alternate whatever symbol or text abstraction in one parameter in order to split your String.

See documentation here.

Here's an example in your case:

String toSplit = "a+b-c*d/e=f";
String[] splitted = toSplit.split("[-+*/=]");
for (String split: splitted) {
    System.out.println(split);
}

Output:

a
b
c
d
e
f

Notes:

  • Reserved characters for Patterns must be double-escaped with \\. Edit: Not needed here.
  • The [] brackets in the pattern indicate a character class.
  • More on Patterns here.
like image 84
Mena Avatar answered Oct 14 '22 15:10

Mena