/* Fichier Ex2String : exemple sur les chaînes de caractères */ public class Ex2String { // méthode qui compte et retourne le nombre de voyelles // dans une phrase déjà transformée en majuscules static int nbVoy(String phrase) { int n = 0; for(int i = 0; i < phrase.length();i++) switch ( phrase.charAt(i)) { case 'A' : case 'E' : case 'I' : case 'O' : case 'U' : case 'Y' : n++; } return n; } // méthode qui compte et retourne le nombre de voyelles // dans une phrase : une autre manière de travail static int nb2Voy(String phrase) { int n = 0; String voyelles = "AaEeIiOoUuYy"; for(int i = 0; i < phrase.length();i++) if ( voyelles.indexOf( phrase.charAt(i)) >= 0) n++; return n; } public static void main(String[] args) { String ch = "Bonjour tout le monde!"; System.out.printf("Le marqueur pour indices: 012345678901234567890123456789\n"); System.out.printf("La chaîne telle quelle : %s\n", ch); System.out.printf("La chaîne en MAJUSCULEs : %s\n", ch.toUpperCase()); System.out.printf("La chaîne en minuscules : %s\n", ch.toLowerCase()); System.out.printf("La longueur : %d caractères\n\n", ch.length()); System.out.printf("Le caractère à l'indice 3 : %c\n", ch.charAt(3)); System.out.printf("La sous-chaîne ch.substring(0, 3) vaut %s\n", ch.substring(0, 3)); System.out.printf("La sous-chaîne ch.substring(8) vaut: %s\n", ch.substring(8)); System.out.printf("Le nombre de voyelles : %d\n", nbVoy(ch.toUpperCase())); System.out.printf("Le nombre de voyelles (solution 2): %d\n\n", nb2Voy(ch)); System.out.printf("La recherche d'un caractère dans la chaîne : %d\n", ch.indexOf('j')); System.out.printf("La recherche d'un caractère dans la chaîne : %d\n\n", ch.indexOf('w')); System.out.printf("La recherche de la sous chaîne mon: %d\n", ch.indexOf("mon")); System.out.printf("La recherche de tremblay: %d\n\n", ch.indexOf("tremblay")); } } /* --------------------Configuration: -------------------- Le marqueur pour indices: 012345678901234567890123456789 La chaîne telle quelle : Bonjour tout le monde! La chaîne en MAJUSCULEs : BONJOUR TOUT LE MONDE! La chaîne en minuscules : bonjour tout le monde! La longueur : 22 caractères Le caractère à l'indice 3 : j La sous-chaîne ch.substring(0, 3) vaut Bon La sous-chaîne ch.substring(8) vaut: tout le monde! Le nombre de voyelles : 8 Le nombre de voyelles (solution 2): 8 La recherche d'un caractère dans la chaîne : 3 La recherche d'un caractère dans la chaîne : -1 La recherche de mon: 16 La recherche de tremblay: -1 Process completed. */