-5

can anyone help me to find a solution to this problem in Java 8:

A string of characters is composed of multiple spaces is given to you. You must remove all unnecessary spaces by writing an algorithm.

Entry: String containing a sentence. Output: String containing the same sentence without unnecessary spaces.

Example: For the following entry: "I (3spaces) live (3spaces) on (3spaces) earth." The output is: "I live on earth."

Mourad Fr
  • 1
  • 1
  • 5
    Welcome to stack overflow. Questions are received best here if you include what you've already tried. An assignment dump like this is not appreciated. Good luck! – Kars Mar 21 '19 at 10:32
  • 1
    What have you tried so far? – Andronicus Mar 21 '19 at 10:33
  • there is no ready made method for this. the existing solutions assume that unless we're talking about leading or trailing spaces, they should be there. You'll have to write your own – Stultuske Mar 21 '19 at 10:33
  • duplicate of https://stackoverflow.com/questions/2932392/java-how-to-replace-2-or-more-spaces-with-single-space-in-string-and-delete-lead – Syed Mehtab Hassan Mar 21 '19 at 10:44

3 Answers3

2

You can use regex for it, e.g.:

String withSpaces = "a   b   c   d";
System.out.println(withSpaces.replaceAll("\\s+", " "));
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

(Note, I liked @Darshan Mehta solution below) You can use regex to replace multiple spaces. I've used: regex101.com in order to test my regex. It then let you generate the regex into a programming language. I've select Java and the result is:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "\\s+";
final String string = "i   live   on   earth";
final String subst = " ";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);
Pam Stums
  • 176
  • 8
  • @Pam_Stums thanks fot your answer but i should not use regex :) by the way can you give me your mail to contact you – Mourad Fr Mar 28 '19 at 11:26
0

Without regex :

String s = "your string";
        StringBuilder sb = new StringBuilder();
        String[] sp = s.split(" ");
        for(String a : sp) {
            if(!a.trim().equals(""))
            sb.append(a+" ");
        }
            System.out.println(sb.toString().trim());   
Ramesh
  • 340
  • 1
  • 7
  • 21