This site requires JavaScript, please enable it in your browser!
Greenfoot back
Busch2207
Busch2207 wrote ...

2012/3/8

Splitting a String

Busch2207 Busch2207

2012/3/8

#
Hey guys! I try to split a String at "." But always, when I write:
        String[] ExampleArray = ExampleString.split(".");
I just get a String array with a length of 0... But it works, when I write:
        ExampleString = ExampleString.replace('.',':');
        String[] ExampleArray = ExampleString.split(":");
But if in the string are some other ":", it splits there, too, of course... What can I do now, without writing an extra method, that checks all the chars...?
Duta Duta

2012/3/8

#
Link Read the section about metacharacters, it might help you
Busch2207 Busch2207

2012/3/8

#
Well thank you for your help... I read through this page... I understand, why it don't work... But it didn't solved my problem...
davmac davmac

2012/3/8

#
Read the page again! :)
There are two ways to force a metacharacter to be treated as an ordinary character: precede the metacharacter with a backslash, or enclose it within \Q (which starts the quote) and \E (which ends it).
Apply that to your code (remembering that in Java, you need to put two backslash characters in your code to generate one in the resulting String).
kiarocks kiarocks

2012/3/8

#
Because the dot is a reserved character, you cannot split the string with it. Instead, use "\\."
davmac davmac

2012/3/8

#
I was going to let him work that out for himself. (but to call the dot a "reserved character" is not quite right. It's just that it has a special meaning in regular expressions, and the split(...) function interprets its argument as a regular expression).
Duta Duta

2012/3/8

#
davmac wrote...
I was going to let him work that out for himself. (but to call the dot a "reserved character" is not quite right. It's just that it has a special meaning in regular expressions, and the split(...) function interprets its argument as a regular expression).
In other words, because it treats the dot as any character, its splitting on all the characters, meaning the array has a 0 size
kiarocks kiarocks

2012/3/8

#
Sorry, confused my terms.
Busch2207 Busch2207

2012/3/8

#
Omg! Now I understand the page, that Duta postet! xD Sry, but I read the page under stress, bevore school today morning and so I haven't thought so much! xD Now it's clear! I haven't thought about, that this was a String and so you need two backslashes instead of one. xD Thank you guys!
You need to login to post a reply.