Home > Mobile >  Remove spaces before a punctuation mark in a string
Remove spaces before a punctuation mark in a string

Time:09-16

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?

CodePudding user response:

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.

CodePudding user response:

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(" \\.", ".");
  • Related