⬆️ ⬇️

Java-puzzle: Capitalization of words in a string in one java-expression

I present to you a little puzzle on Java.

This is a real task that has arisen before me and my 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 words of an arbitrary string.



That is, something like this:

String strOrig = " ";

String strRes = <.. - ..>;

assert strRes.equals(" ");



Our solution to the puzzle turned out to be very interesting and I decided to give the community the opportunity to offer my own ways to solve this problem.

Waiting for your suggestions!

')

The results of brain activity under the cat



Mr alex14n and Mr Daymz have proposed a solution using anonymous classes that fully satisfies the problem condition:

String strRes = (new Object() {

public String work(String string) {

/* */

}

}).work(strOrig);




Well, the most beautiful solution (similar to ours) was proposed by Mr. trg .

A little earlier, a man with the nickname Blazkowicz hit him in Asya, proposing the same method:

String strRes = String.format(strOrig.replaceAll("\\b(\\S)", "%S"), (Object[]) strOrig.replaceAll("\\b(\\S)\\S*", "$1").split("\\s+"));



Another solution using only replays suggested by Daymz :

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);




Thank you all for your interest!

Source: https://habr.com/ru/post/72461/



All Articles