[Abstract: I need a way to remove the newline token (\n) from a massive string, hopefully without regex]

For my CS class, we have to read in a maze from a text file, which would look something like this:

##############################
#@...........................#
##############################
##############################
##############################
##############################
##############################
##############################
##############################
##############################
------------------------------
##############################
##############################
#@...........................#
##############################
##############################
##############################
##############################
##############################
##############################
##############################
------------------------------
##############################
##############################
##############################
#@...........................#
##############################
##############################
##############################
##############################
##############################
##############################
------------------------------

The dashed Lines indicate separate floors. It's a 3D maze.

This is just a test for reading the maze, so the pieces are irrelevant. We have to read the entire maze into a single string using the Scanner class, but then we have to be able to test each individual (x,y,z) and return what character exists at that point. My idea is to separate the huge string into a 3-dimensional array of chars (char[][][]), but that requires removing the newline characters from the huge maze string. Is there a way I can remove the \n tokens from the massive string, hopefully without using regex. I've looked around a lot, but can't quite find a solid answer. A lot of people suggest using regex, but I'm not too familiar with doing that and would like to avoid it if possible. Thanks for all your help.

有帮助吗?

解决方案

Use replace:

String input="###...##";
String output=input.replace("\n","");

其他提示

If you read lines as Strings, you can use the trim() method:

String line = "...\n".trim();

public String trim(): Returns a copy of the string, with leading and trailing whitespace omitted.

Java will recognise the new line character as a single character, i.e, "\n" is a single character. So I guess if you use a scanner to read each character then you can include an if condition along with it so that whenever a new line character is detected, it will ignore it. Something like:

if(character!="\n")
{
    //your code to keep the character into the array
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top