Práce s řetězci

Úvod do Javy

Jim White

Java Developer

Rekapitulace String

Řetězce mají vestavěnou funkcionalitu pro jejich manipulaci

Úvod do Javy

String.length()

  • Počet znaků v Stringu = délka Stringu
  • String.length() vrací int s počtem znaků
String userName = "JSmith13";

int userNameLength = userName.length(); // Value is 8
Úvod do Javy

Změna velikosti písmen

.toLowerCase()

  • Převede všechna písmena na malá
class StringMethods1 {
  public static void main (String[] args){

    String yes = "Yes";
    System.out.println(yes.toLowerCase());

  }
}
yes

.toUpperCase()

  • Převede všechna písmena na velká
class StringMethods2 {
  public static void main (String[] args){

    String yes = "Yes";
    System.out.println(yes.toUpperCase());

  }
}
YES
Úvod do Javy

Zřetězení řetězců

  • Pomocí + lze spojit dva Stringy dohromady
class StringMethodsCont {
  public static void main (String[] args){

    String message1 = "Java is";
    String message2 = "awesome";
    // Use " " to nicely format the final message
    System.out.println(message1 + " " + message2);
  }
}
Java is awesome
Úvod do Javy

Zřetězení s čísly

  • + automaticky převede číslo na String, pokud je použit s Stringem
class StringMethodsCont {
  public static void main (String[] args){

    String message1 = "Java is";
    int message2 = 29;
    // Use " " to nicely format the final message
    System.out.println(message1 + " " + message2);
  }
}
Java is 29
Úvod do Javy

Deklarovat nyní, přiřadit později

  • Deklarujte proměnnou bez přiřazení hodnoty, hodnotu přiřaďte později
  • Užitečné pro
    • Velké množství textu
    • Pokud hodnota ještě není známa
    • Efektivní strukturování kódu
// Define now
String courseCreators;



// Assign value later courseCreators = "Instructor: Jim White; Collaborators: Kat, George, Arne, Eduardo";
Úvod do Javy

Rekapitulace

  • String = kolekce znaků v uvozovkách s vestavěnou funkcionalitou
// Declare now
String testMessage;
// Assign later
testMessage = "This is a test";

// Method to return the String's length (number of characters)
int msgLength = testMessage.length(); // Value is 14

// Methods to convert String to lower or upper case
String lowerMessage = testMessage.toLowerCase(); // Value is "this is a test"

String upperMessage = testMessage.toUpperCase(); // Value is "THIS IS A TEST"
Úvod do Javy

Lass uns üben!

Úvod do Javy

Preparing Video For Download...