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

Recommended Answers

All 5 Replies

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.

| 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. [|] )
commented: Haha! I knew that | = or, but couldn't recall it at the time. +4

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.