1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public static String capitalize(String text) {
// On crée notre pattern
// (Note : en cas d'appel multiple il peut être intérressant
// de stocker le Pattern pour le réutiliser)
Pattern pattern = Pattern.compile("\\b\\p{Ll}");
// On crée le matcher qui va parcourir notre texte :
Matcher matcher = pattern.matcher(text);
// Si on trouve au moins un élément :
if (matcher.find()) {
// On crée un StringBuffer qui va contenir la nouvelle chaine :
StringBuffer sb = new StringBuffer(text.length());
// Puis pour chaque élément trouvé :
do {
// On récupère l'élément courant :
String val = matcher.group();
// Et on effectue le remplacement :
matcher.appendReplacement(sb, val.toUpperCase());
} while (matcher.find());
// A la fin, on copie tel quel le texte restant :
matcher.appendTail(sb);
// Et on retourne la nouvelle chaine
return sb.toString();
}
// Sinon, cela signifie qu'il n'y a pas besoin de modif,
// Et on retourne directement la chaine :
return text;
} |
Partager