Hi. Im working on a text-based "game" that uses strings to generate maps. So I need to split these strings into bits that i can work with, but somehow the .split method kills the white space in my string. How can I get around this? Of course I can force my way round by doing it all with characters instead, but it would be a lot easier and probably less computing intensive to get the .split to work. Here is a sample of what I do:

String map1 = "########|# #. #|# $# #|# # @##|# # $##|# .##|########";

String handleMap[] = map1.split("|");

(fantastic, even the forum kills my white space:P There are equal amounts of characters inbetween the "|". So there is really 8 characters inbetween all the "|".)

Thanks for the help

If you're using Scanner's next() method to read in the String, it is probably killing your whitespace. http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#next%28%29 . Keep in mind that the default delimiter pattern matches whitespace, so your 'tokens' that it refers to in the method documentation is preceded and followed by whitespace. Do you mind posting your code?

Also, you should try this:

yourString.split("[|]");

You should look into java's regular expressions tutorial, but using "|" seems to not work, while what I have above does.

Edited 6 Years Ago by BestJewSinceJC: n/a

| has a special meaning when it comes to regular expressions, it's called the alternation symbol.

If you have something like "##|##|##".split("|") , it's the same as "##|##|##".split("") since a single pipe symbol is the same as saying "alternate between a blank string and another blank string" which is the same as a blank string.

You can either:

  • Escape this pipe character and tell the regex engine to treat is at a literal pipe character. Something like "string".split("\\|")
  • Use character classes, similar to the example posted above (i.e. [|] )

Edited 6 Years Ago by ~s.o.s~: n/a

Comments
Haha! I knew that | = or, but couldn't recall it at the time.

Both the "[|]" and the "\\|" worked! Nice:) Thanks a lot. Now I can finish my homework :D

And BestJewSinceJC, I don't use the scanner, it is a hardcoded string (the map of my game).

Thanks again!

When you pass a string to .split instead of a regex, it uses that string to create a regex, instead of using the original string object you've passed.
This is a bug I make every possible time. :S

Edited 6 Years Ago by MoZo1: n/a

When you pass a string to .split instead of a regex, it uses that string to create a regex, instead of using the original string object you've passed.
This is a bug I make every possible time. :S

Huh? Every String you "pass to split" is a regex, whether you intended it to be one or not.

This question has already been answered. Start a new discussion instead.