Java Strings in 10 minutes Declaringcreating a new










- Slides: 10

Java Strings in 10 minutes

Declaring/creating a new String str. Name = ""; String str = "WLCS"; String str 2 = "Hello"; //String is the type name

Size/length of a string String str = "WLCS"; System. out. println( str. length() ); //returns 4

String Library of Methods o Strings have many pre-made methods in Java o Examples n n length() equals() substring() Etc. o Java String Library

Comparing if Strings are equal o == does NOT work o Must use the. equals() method str 2. equals("Hello"); //returns true str. Name. equals(str 2); //return false

Substrings (Strings slices) o str. Name. substring(a, b) n Returns a substring from index a up to b (exclusive) String str = "Hello, world"; System. out. println( str. substring(0, 5) ); //returns Hello System. out. println( str. substring(7, str. length()) ); //returns World

Searching for a substring o str. Name. index. Of(String substr) returns the index of the specific substr String str = "Hello, world"; System. out. println( str. index. Of(", ") ); //returns 5 System. out. println( str. index. Of("wo") ); //returns 7 System. out. println( str. index. Of("qwerty") ); //returns -1

Comparing Strings alphabetically o str. Name. compare. To(String str) returns an integer indicating alphabetical order String str 1 = "abc"; String str 2 = "def"; System. out. println(str 1. compare. To(str 2)); //returns -3 System. out. println(str 1. compare. To(str 1)); //returns 0 System. out. println(str 2. compare. To(str 1)); //returns 3

compare. To() example String str 1 = "abc"; String str 2 = "def"; if (str 1. compare. To(str 2) < 0) { System. out. println(str 1 + " goes before " + str 2); }

Other useful String methods o o to. Lower. Case() to. Upper. Case() trim() split() o Oracle Java String Documentation n http: //docs. oracle. com/javase/8/docs/ap i/java/lang/String. html