Shrey Varma
Shrey Varma

Reputation: 69

I'm trying to get rid of spaces and convert a text file into a single line

I was able to convert the text file input into a single line but could not get rid of the spaces no matter what I did and I've tried using .trim(), .strip(), and regex. Here is the original input(example.in):

    ..........
    ..........
    ..........
    ..B.......
    ..........
    .....R....
    ..........
    ..........
    .....L....
    ..........

My code:

    String in = Files.readString(Paths.get("example.in"));
    in=in.replaceAll("[\r\n\\s]+", " ");

Output:

    .......... .......... .......... ..B....... .......... .....R.... .......... .......... .....L.... ..........

Upvotes: 0

Views: 233

Answers (1)

Abhinav Chauhan
Abhinav Chauhan

Reputation: 1384

following regex converts all newline in empty string and tabs in spaces

in = in.replaceAll("\\n","").replaceAll("\\t"," ");

if you have other kind of white spaces then you can chain in the same way

EDIT

one more thing if you have consecutive spaces then chain replaceAll("\\s+," ");

in short you can say in = in.replaceAll("\\n|\\t|\\s"," ");

Upvotes: 1

Related Questions