Home > database >  remove space before and after - in the string
remove space before and after - in the string

Time:06-01

I am trying to remove extra spaces in the string.To achieve this I used normalizeSpace method in StringUtils class. But the problem is it is not removed the spaces before and after "-"

public static void main(String[] args)
{
String test = "  Hi   -  World    Java";
System.out.println(StringUtils.normalizeSpace(test));
}

Output as: "Hi - World Java" The expected output is: "Hi-World Java"

Any inputs?

Note: Below ticket solution is during concatenating strings. Where as we have data in a single string. So this ticket is not a duplicate ticket. Remove spaces before a punctuation mark in a string

CodePudding user response:

test = test.replaceAll("[  ] "," ");
test = test.replaceAll("- ","-");
test = test.replaceAll(" -","-");
test = test.replaceAll("^\\s ",""); 

CodePudding user response:

The utility removes all extra spaces but leaves one space. In other words where it find a sequence of more than one space it removes all but one space. So your result is as expected. If you need it the way you wrote: "Hi-World Java" then you need your own logic, as specified in some other answers here.

  • Related