javastringapache-stringutils

remove space before and after - in the string


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


Solution

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