Java Strings in 5 minutes

advertisement
Java Strings in 10 minutes
Declaring/creating a new String
String strName = "";
String str = "WLCS";
String str2 = "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
 Strings have many pre-made
methods in Java
 Examples




length()
equals()
substring()
Etc.
 Java String Library
Comparing if Strings are equal
 == does NOT work
 Must use the .equals() method
str2.equals("Hello"); //returns true
strName.equals(str2); //return false
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
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
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
compareTo() example
String str1 = "abc";
String str2 = "def";
if (str1.compareTo(str2) < 0)
{
System.out.println(str1 + " goes before " + str2);
}
Other useful String methods




toLowerCase()
toUpperCase()
trim()
split()
 Oracle Java String Documentation
 http://docs.oracle.com/javase/8/docs/ap
i/java/lang/String.html
Download