Skip to main content
1 of 4
Chris
  • 4.7k
  • 1
  • 7
  • 36

It strikes me that the simplest method to do this is to leverage the standard library.

public final class TextSpaceCompressor {
    public static String spaceCompress(String text) {
        return text.strip().replaceAll("\\s+", " ");
    }
}

Now, this will also remove newlines. Your test examples indicate you're okay doing this, but if you wanted to preserve newlines you could use streams to map over the lines, perform the substitutions and then collect the string back together, joining with newlines.

import java.util.stream.Collectors;

public final class TextSpaceCompressor {
    public static String spaceCompress(String text) {
        return text
            .lines()
            .map(line -> line.strip().replaceAll("\\s+", " "))
            .collect(Collectors.joining("\n"));
    }
}
Chris
  • 4.7k
  • 1
  • 7
  • 36