Try this:
String after = before.trim().replaceAll(" +", " ");
See also
String.trim()- Returns a copy of the string, with leading and trailing whitespace omitted.
- regular-expressions.info/Repetition
No trim() regex
It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
There are 3 alternates:
^_+: any sequence of spaces at the beginning of the string- Match and replace with
$1, which captures the empty string
- Match and replace with
_+$: any sequence of spaces at the end of the string- Match and replace with
$1, which captures the empty string
- Match and replace with
(_)+: any sequence of spaces that matches none of the above, meaning it's in the middle- Match and replace with
$1, which captures a single space
- Match and replace with
See also
- regular-expressions.info/Anchors
Try this:
String after = before.trim().replaceAll(" +", " ");
See also
String.trim()- Returns a copy of the string, with leading and trailing whitespace omitted.
- regular-expressions.info/Repetition
No trim() regex
It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:
String[] tests = {
" x ", // [x]
" 1 2 3 ", // [1 2 3]
"", // []
" ", // []
};
for (String test : tests) {
System.out.format("[%s]%n",
test.replaceAll("^ +| +$|( )+", "$1")
);
}
There are 3 alternates:
^_+: any sequence of spaces at the beginning of the string- Match and replace with
$1, which captures the empty string
- Match and replace with
_+$: any sequence of spaces at the end of the string- Match and replace with
$1, which captures the empty string
- Match and replace with
(_)+: any sequence of spaces that matches none of the above, meaning it's in the middle- Match and replace with
$1, which captures a single space
- Match and replace with
See also
- regular-expressions.info/Anchors
You just need a:
replaceAll("\\s{2,}", " ").trim();
where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).
To test this out quickly try:
System.out.println(new String(" hello there ").trim().replaceAll("\\s{2,}", " "));
and it will return:
"hello there"
[Java] Removing extra whitespace from a string and counting words in a string?
Ways to remove spaces from a string using JavaScript
How to remove all spaces from a string in Java?
How can I remove all whitespace from a Java string using Java Streams?
How to remove whitespace from the beginning and end of a string in Java?
Hello all,
I am a college student taking my first programming class, and need help with some parts of an assignment, and was hoping I could get some help here. In the program we're writing, the user is prompted for a string, and then we must delete all extra whitespace between the words (so no trim), as well as making sure the sentence meets the minimum word count.
Here is what I have written for the word counter, but it seems really bulky, and it also doesn't count words if they are proceeded by a comma or other (valid) non-letter character:
//Error for a sentence with too few words.
int wordCountStart = 0;
int wordCount = 1;
char b = sentence.charAt(wordCountStart);
while (wordCountStart < sentence.length())
{
while ((b == ' ') || (b == '(') || (b == ')') || (b == '.') || (b == '?') || (b == '!') || (b == ',') || (b == '/') || (b == '"') || (b == '[') || (b == ']') || (b == '-') || (b == ':') || (b == ';') ||(b == '\''))
{
wordCountStart ++;
if (wordCountStart == sentence.length()) break;
b = sentence.charAt(wordCountStart);
}
while (Character.isLetter(b))
{
wordCountStart ++;
if (wordCountStart == sentence.length()) break;
b = sentence.charAt(wordCountStart);
}
if (b == ' ')
{
wordCount ++;
}
}
if (wordCount < 7)
{
JOptionPane.showMessageDialog(null, "Your sentence needs to contain at least 7 words.", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}