Java string CamelCase traitement

Fermé
Flog78 - 23 janv. 2013 à 14:30
KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 - 23 janv. 2013 à 15:33
Bonjour,

je cherche à convertir une chaine de caractère string en entrée sous forme camelCase
ex : monNomDeVariable
sous cette forme
ex : mon_Nom_De_Variable

J'ai essayé
str.split("[a-z][A-Z]");
mais ca me tronque les premierre lettres : mo_o__ariable

J'ai essayé
str.replaceAll("[a-z][A-Z]", "_");
mais pareil j'obtient : mo_o__ariable
A voir également:

1 réponse

KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015
23 janv. 2013 à 15:33
Pourquoi s'embêter avec des expressions régulières quand une petite boucle suffit ?

public static String convert(String str)
{
	StringBuilder sb = new StringBuilder();
	for (char c : str.toCharArray())
	{
		if (Character.isUpperCase(c))
			sb.append('_');
		sb.append(c);
	}
	return sb.toString();
}
1