Šiame pavyzdyje mes išmoksime paversti pirmąją eilutės raidę didžiosiomis „Java“ raidėmis.
Norėdami suprasti šį pavyzdį, turite žinoti šias Java programavimo temas:
- „Java“ eilutė
- „Java“ eilutė toUpperCase ()
1 pavyzdys: „Java“ programa pirmosios eilutės didžiosios raidės sudarymui
class Main ( public static void main(String() args) ( // create a string String name = "programiz"; // create two substrings from name // first substring contains first letter of name // second substring contains remaining letters String firstLetter = name.substring(0, 1); String remainingLetters = name.substring(1, name.length()); // change the first letter to uppercase firstLetter = firstLetter.toUpperCase(); // join the two substrings name = firstLetter + remainingLetters; System.out.println("Name: " + name); ) )
Rezultatas
Pavadinimas: Programiz
Pavyzdyje mes pavertėme pirmąją eilutės pavadinimo raidę didžiosiomis raidėmis.
2 pavyzdys: paverskite kiekvieną eilutės žodį didele
class Main ( public static void main(String() args) ( // create a string String message = "everyone loves java"; // stores each characters to a char array char() charArray = message.toCharArray(); boolean foundSpace = true; for(int i = 0; i < charArray.length; i++) ( // if the array element is a letter if(Character.isLetter(charArray(i))) ( // check space is present before the letter if(foundSpace) ( // change the letter into uppercase charArray(i) = Character.toUpperCase(charArray(i)); foundSpace = false; ) ) else ( // if the new character is not character foundSpace = true; ) ) // convert the char array to the string message = String.valueOf(charArray); System.out.println("Message: " + message); ) )
Rezultatas
Žinutė: visi mėgsta „Java“
Čia
- mes sukūrėme eilutę pavadinimu pranešimas
- eilutę pavertėme
char
masyvu - prieiname prie kiekvieno
char
masyvo elemento - jei elementas yra baltas tarpas, kitą elementą paverčiame didžiąja raide