0
public class Main {
    public static void main(String[] args) {
        String[] words = {"The", "quick", "brown", "fox", ",", "jumps", "over", "the", "lazy", "dog", "."};
        String concatenatedString = "";

        for (String word : words) {
            concatenatedString += word + " ";
    }
    
        System.out.println(concatenatedString);
}

}

I am trying to concatenate all the words from a string array in a single string, and the output I get is like this : "The quick brown fox , jumps over the lazy dog ."

I would want the spaces before punctuation marks to be removed so the output could look like this : "The quick brown fox, jumps over the lazy dog." Any idea how could I do that?

  • 1
    `s = s.replaceAll("\\s+(\\p{Punct})", "$1");` – Joop Eggen Sep 15 '21 at 14:03
  • Did you make any attempts? If do, please post them and explain why they don't do what you want – Erwin Bolwidt Sep 15 '21 at 14:04
  • If you want to rather _not_ insert a space in the first place rather deleting them afterwards, you'll need to know the "following word" while iterating to decide whether a space should be added, so I'd rather use a good old `for (i < n)` loop so that you have access to `i+1`. Be careful with `ArrayIndexOutOfBoundsException` though. – sp00m Sep 15 '21 at 14:05

4 Answers4

1

By programming it. Why is quick and brown eligible for separation with a space, but fox and , isn't? Java obviously doesn't know. You'd have to tell it. You can use str.charAt(0) to get the first character, str.charAt(str.length() -1) for the last, you can use Character.isLetterOrDigit to check if it's the kind of character where you'd want a space (e.g. NOT a colon or a space or a comma or an exclamation mark or any other such).

Use these tools inside your for (String word : words) loop. Determine if the start of the string you're about to add is a 'non letter/digit' and if so, do not add that space. Otherwise add it.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
0

As you are concatenating the chars with an space, you can make a replacement on the string variable to remove the spaces you dont want

concatenatedString = concatenatedString.replaceAll(" ,", ",")
       .replaceAll(" \\.", ".");
Francisco Valle
  • 613
  • 10
  • 10
  • 2
    This is inefficient, kinda weird (first do the wrong thing, then fix the mistake), and only works for commas, not for e.g. semicolons, colons, newlines, spaces, and a million other symbols. – rzwitserloot Sep 15 '21 at 14:06
  • 1
    Ineffiency is not so important here. But in this case `replace` instead of `replaceAll` would suffice. Or a bit more regex `replaceAll(" ([,;.:!?])", "$1")`. – Joop Eggen Sep 15 '21 at 14:12
0

I would flip your logic so that you prepend a space if the word being added needs one before it. You will have to handle the initial word not needing one (you could either check if concatenatedString is empty, or simply start out concatenatedString as the first word and skip to the second).

As it is now, you have two problems:

  1. The word you have to check is the next word, not the current word, and
  2. you're ending up with a trailing space on the string, which is there even if it doesn't show up in the print.

If you switch to prepending spaces on adding a new word, it makes it much easier to check. Then only add a space before the word if it's a word that needs a space.

jaynabonne
  • 1,131
  • 2
  • 7
  • 3
  • Or i could use trim on the string – Alex Darius Sep 20 '21 at 14:00
  • Sure, you could. That would sort of work around the fact that you're adding a space when you don't need to. It would certainly work if that's all you had to do. But if you ever expanded the code to handle more cases, that sort of quick fix could come back to bite you, as opposed to a simple restructure of the code that's in line with what you need to do (add a space when adding a word if there is already a word and the new word needs a space). – jaynabonne Sep 21 '21 at 16:30
0

As an exercise, I thought I'd give this a shot. Taking the code you provided as a template, I used the strategy of optionally prepending a space depending on the contents of the current string, as suggested by jaynabonne in a posting above.

    final private static String optionalPrefixOf(String word)
    {
        if (Character.isLetterOrDigit(word.charAt(0)))
            return " ";
        else
            return "";
    }

    public static void main(String[] args) {
        String[] words = {"The", "quick", "brown", "fox", ",", "jumps", "over", "the", "lazy", "dog", "."};
        String concatenatedString = "";

        for (String word : words) {
            if (concatenatedString.isEmpty()) {
                concatenatedString = word;
            }
            else {
                concatenatedString += optionalPrefixOf(word) + word;
            }
        }

        System.out.println(concatenatedString);
    }
}