JustForLong
JustForLong

Reputation: 109

How can I split apart a string that has different amount of spaces into two parts?

I wanted to split one half to be a String mimeType and second half to be String ext

so far I implemented (str being the individual lines)

String mimeType="";
String ex = "";

String[] strArr = str.split("\t\t\t");

mimeType = strArr[0];
ex = strArr[1];

Since some don't have a second part, I keep getting errors. How do I go about fixing that?

audio/vnd.octel.sbc
audio/vnd.qcelp
audio/vnd.rhetorex.32kadpcm
audio/vnd.vmx.cvsd
audio/x-pn-realaudio-plugin rpm
audio/x-realaudio       ra
audio/x-wav         wav
chemical/x-pdb          pdb
chemical/x-xyz          xyz
image/bmp           bmp
image/cgm           cgm
image/g3fax
image/gif           gif
image/ief           ief
image/jpeg          jpeg jpg jpe

Upvotes: 1

Views: 50

Answers (2)

Jakob F
Jakob F

Reputation: 1056

Use \\s+ to split on spaces even if they're are multiple.

String mimeType="";
String ex = "";

String[] strArr = str.split("\\s+");

mimeType = strArr[0];
ex = strArr[1];

Upvotes: 0

AndiCover
AndiCover

Reputation: 1734

Just check the length of the array:

String[] strArr = str.split("\t\t\t");
mimeType = strArr[0];

if(strArr.length >= 2) {
    ex = strArr[1];
} else {
    ex = "None";
}

Upvotes: 2

Related Questions