Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Strings in 10 minutes

Similar presentations


Presentation on theme: "Java Strings in 10 minutes"— Presentation transcript:

1 Java Strings in 10 minutes

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

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

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

5 Comparing if Strings are equal
== does NOT work Must use the .equals() method str2.equals("Hello"); //returns true strName.equals(str2); //return false

6 Substrings (Strings slices)
strName.substring(a,b) 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

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

8 Comparing Strings alphabetically
strName.compareTo(String str) returns an integer indicating alphabetical order String str1 = "abc"; String str2 = "def"; System.out.println(str1.compareTo(str2)); //returns -3 System.out.println(str1.compareTo(str1)); //returns 0 System.out.println(str2.compareTo(str1)); //returns 3

9 compareTo() example String str1 = "abc"; String str2 = "def";
if (str1.compareTo(str2) < 0) { System.out.println(str1 + " goes before " + str2); }

10 Other useful String methods
toLowerCase() toUpperCase() trim() split()


Download ppt "Java Strings in 10 minutes"

Similar presentations


Ads by Google