Reputation: 1
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?
Upvotes: 0
Views: 688
Reputation: 1
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);
}
}
Upvotes: 0
Reputation: 1131
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:
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.
Upvotes: 0
Reputation: 103707
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.
Upvotes: 1
Reputation: 643
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(" \\.", ".");
Upvotes: 0