W tym przykładzie nauczymy się konwertować pierwszą literę ciągu na wielką w Javie.
Aby zrozumieć ten przykład, należy znać następujące tematy dotyczące programowania w języku Java:
- Ciąg Java
- Ciąg Java toUpperCase ()
Przykład 1: Program w języku Java, który tworzy pierwszą literę w postaci ciągu znaków
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); ) )
Wynik
Nazwa: Programiz
W tym przykładzie przekonwertowaliśmy pierwszą literę nazwy ciągu na wielką.
Przykład 2: Zamień każde słowo w łańcuchu na wielkie litery
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); ) )
Wynik
Wiadomość: Wszyscy kochają Javę
Tutaj,
- stworzyliśmy ciąg o nazwie wiadomość
- przekonwertowaliśmy ciąg na
char
tablicę - mamy dostęp do każdego elementu
char
tablicy - jeśli element jest spacją, konwertujemy następny element na wielkie litery