I have a string that looks like this:
CALDARI_STARSHIP_ENGINEERING
and I need to edit it to look like
Caldari Starship Engineering
Unfortunately it's three in the morning and I cannot for the life of me figure this out. I've always had trouble with replacing stuff in strings so any help would be awesome and would help me understand how to do this in the future.
Something like this is simple enough:
String text = "CALDARI_STARSHIP_ENGINEERING";
text = text.replace("_", " ");
StringBuilder out = new StringBuilder();
for (String s : text.split("\\b")) {
if (!s.isEmpty()) {
out.append(s.substring(0, 1) + s.substring(1).toLowerCase());
}
}
System.out.println("[" + out.toString() + "]");
// prints "[Caldari Starship Engineering]"
This split
on the word boundary anchor.
Matcher
loop solutionIf you don't mind using StringBuffer
, you can also use Matcher.appendReplacement/Tail
loop like this:
String text = "CALDARI_STARSHIP_ENGINEERING";
text = text.replace("_", " ");
Matcher m = Pattern.compile("(?<=\\b\\w)\\w+").matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, m.group().toLowerCase());
}
m.appendTail(sb);
System.out.println("[" + sb.toString() + "]");
// prints "[Caldari Starship Engineering]"
The regex uses assertion to match the "tail" part of a word, the portion that needs to be lowercased. It looks behind (?<=...)
to see that there's a word boundary \b
followed by a word character \w
. Any remaining \w+
would then need to be matched so it can be lowercased.
\l
\u
, \L
, and \U
. appendReplacement/Tail
only takes StringBuffer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With