1

I want only one space in output between every word no matter how much spaces between the words in input. But in following code spaces in output between love and java same as input spaces.

public class Main {
    public static void main(String[] args) {
        String s = "I love       java programming.";

        String ss[] = s.split(" ");
        for (int i = ss.length - 1; i >= 0; i--) {
            System.out.print(ss[i] + " ");
        }
    }
}

Output:--

programming. java       love I 
ernest_k
  • 44,416
  • 5
  • 53
  • 99

2 Answers2

2

I completely agree with @Johannes Kuhn.

The problem is, the filter you passed to the method split detects only single spaces.

This can be solved easily by passing correct regex expression to detect multiple spaces and dots and the end of the sentence.

Have a look at the following implementation:

public class Main {

    public static void main(String[] args) {
        String s = "I love       java programming.";

        String ss[] = s.split("[\\.| ]+");
        for (int i = ss.length - 1; i >= 0; i--) {
            System.out.print(ss[i] + " ");
        }
    }
}

PS: You can use "[ ]+" if dots doesn't matter to you.

Deepak Tatyaji Ahire
  • 4,883
  • 2
  • 13
  • 35
0

Small variation using StringBuilder and Lambdas

import java.util.Arrays;

class Main {

  public static void main(String ... args) {

    var s = "I love     java programming";
    var r = new StringBuilder();
    var parts = s.split("\\s +");
    Arrays.asList(parts).forEach(r::append);
    System.out.println(r.reverse().toString());

  }
}

Output: gnimmargorp avajevol I

Repl

OscarRyz
  • 196,001
  • 113
  • 385
  • 569