
Java puzzle: Capitalize words in a string in one java expression
I present to you a small jigsaw puzzle in Java.
This is a real task that arose before me and colleagues in the development process and has a completely justified application.
So, the condition:
It is necessary to implement ONE Java expression (of course, using only standard libraries) the task of capitalizing arbitrary string words.
That is, something like this: Our puzzle solution turned out to be very interesting and I decided to provide the community with the opportunity to offer my own ways to solve this problem. Waiting for your assumptions! Brain results under the cut Mr. Alex14n and Mr. Daymz
proposed a solution using anonymous classes that completely satisfies the condition of the problem: Well, a beautiful solution (similar to ours) was proposed by Mr. trg . A little earlier than him, a man with the nickname Blazkowicz bumped into Asya, proposing the same method: Another solution using only ripleys was offered by Daymz : Thank you all for your interest!
This is a real task that arose before me and colleagues in the development process and has a completely justified application.
So, the condition:
It is necessary to implement ONE Java expression (of course, using only standard libraries) the task of capitalizing arbitrary string words.
That is, something like this: Our puzzle solution turned out to be very interesting and I decided to provide the community with the opportunity to offer my own ways to solve this problem. Waiting for your assumptions! Brain results under the cut Mr. Alex14n and Mr. Daymz
String strOrig = "строка с большим количеством слов";
String strRes = <.. тут какое-то выражение ..>;
assert strRes.equals("Строка С Большим Количеством Слов");
proposed a solution using anonymous classes that completely satisfies the condition of the problem: Well, a beautiful solution (similar to ours) was proposed by Mr. trg . A little earlier than him, a man with the nickname Blazkowicz bumped into Asya, proposing the same method: Another solution using only ripleys was offered by Daymz : Thank you all for your interest!
String strRes = (new Object() {
public String work(String string) {
/* а тут много кода */
}
}).work(strOrig);
String strRes = String.format(strOrig.replaceAll("\\b(\\S)", "%S"), (Object[]) strOrig.replaceAll("\\b(\\S)\\S*", "$1").split("\\s+"));
String strRes = (" " + strOrig)
.replaceAll(
"\\s\\S+",
"$0 " + strOrig
.replaceAll("\\s", "")
.replaceAll("\\\\", "\\\\\\\\")
.replaceAll("\\$", "\\\\\\$")
.toUpperCase()
)
.replaceAll("(?i)(\\s)(\\S)(\\S*) \\S*(\\2)(\\S*)", "$1$4$3")
.substring(1);