Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split function not working properly

Tags:

java

I am trying to split the string using Split function in java

String empName="employee name | employee Email";
String[] empDetails=empName.split("|");

it gives me result as

empDetails[0]="e";
empDetails[1]="m";
empDetails[2]="p";
empDetails[3]="l";
empDetails[4]="o";
empDetails[5]="y";
empDetails[6]="e";
empDetails[7]="e";
.
.
.

but when i try following code

String empName="employee name - employee Email";
String[] empDetails=empName.split("-");

it gives me

 empDetails[0]="employee name ";
 empDetails[1]=" employee Email";

why java split function can not split the string seperated by "|"

like image 726
Abhijit Avatar asked Nov 30 '22 00:11

Abhijit


1 Answers

String#split() method accepts a regex and not a String.

Since | is a meta character, and it's have a special meaning in regex.

It works when you escape that.

String[] empDetails=empName.split("\\|");

Update:

Handling special characters in java:OFFICIAL DOCS.

As a side note:

In java method names starts with small letters.it should be split() not Split() ..not the capital and small s

like image 73
Suresh Atta Avatar answered Dec 09 '22 15:12

Suresh Atta