I am working on a format parser in Java and have some trouble with that. The format is stored so that users can change it to their likings.
format: '[prefix] [name] [suffix]: [msg]'
To put my values in the format I use String.replace() in Java.
format = getFormatTemplate(); // '[prefix] [name] [suffix]: [msg]'
format = format.replace("[prefix]", prefix); // prefix = "Hello";
format = format.replace("[name]", name); // name = "username";
format = format.replace("[suffix]", suffix); // suffix = "World";
format = format.replace("[msg]", msg); // msg = "Test message";
This will result in the output Hello username World: Test message as I expect.
But when some parts of the string are empty there will be a space there.
When for example the suffix is empty the output will be Hello username : Test message note the space between the name and the :
How can I get rid of that so that some parts can be empty without breaking the user defined format?
Is there a better way to parse and apply the format?