/**
* {@link <a href=
* "https://[Log in to view URL]"
* target="_blank"> formattazione di una classe </a>}
*
* @author itammb ( Italia Massimiliano Buscati )
* @version JDK 1.15
*
*/
class Main {
public static class Parser {
/**
* @return Testo alfanumerico senza spazi bianchi duplicati
*
* @see Character#isWhitespace(char)
* @see String#charAt(int)
*
*/
public static String equalizeWhitespace(String text) {
StringBuffer buffer = new StringBuffer();
boolean lastIsNotWhiteSpace = true;
for (int i = 0; i < text.length(); i++)
lastIsNotWhiteSpace = appendCharacter(buffer, text.charAt(i), lastIsNotWhiteSpace);
return buffer.length() == 0 ? "" : buffer.toString();
}
private static boolean appendCharacter(StringBuffer buffer, char character, boolean lastIsNotWhiteSpace) {
if (!Character.isWhitespace(character)) {
buffer.append(character);
return true;
} else if (lastIsNotWhiteSpace) {
buffer.append(' ');
}
// Se il carattere rilevato è uno spazio bianco
// ( LINE FEED, FORM FEED, HORIZONTAL TABULATION, ecc... )
// lo sostituisce con il carattere SPACE_SEPARATOR.
// I duplicati adiacenti sono eliminati dallo stream, negli step sucessivi.
return false;
}
}
public static void main(String[] args) {
// unit test - inseriti 3 spazi all'inizio: # I sogni#
// unit test - inseriti 3 spazi alla fine : #Joyce #
// unit test - inseriti 3 spazi in mezzo : # Essi#
String text = " I sogni non esistono nel regno delle ore e dei minuti, o in qualsiasi misura del "
+ "giorno...\r\n Essi vivono tra il tic tac...Prima del rintocco della campana, oltre "
+ "l'alba e oltre la notte di velluto...\r\n William Joyce ";
String text_ = Parser.equalizeWhitespace(text);
System.out.println(text);
System.out.println(text_);
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: