Transcript String

String Processing in Java
Computer Science 3
String is a class
• In Java, String is a class
– Built in to Java
– Manipulated via methods like any Java class
• Methods defined on the String class
–
–
–
–
–
equals()
length()
substring()
indexOf()
compareTo()
Equals Method
• Takes a single parameter, a String
• Returns a boolean
– True if the String parameter matches the object
equals() is invoked on, false otherwise
– Example:
String foo = “abc”;
foo.equals(“abc”) // Evaluates to true
foo.equals(“xyz”) // Evaluates to false
Length() Method
• Takes no parameters
• Returns an integer, the length of the string
on which it was called
• For example:
String s1= “abcde”;
String s2= “ghij”;
System.out.print(s1.length());//5
System.out.print(s2.length());//4
substring() Method
• Used to get a portion of an existing string
• Can have 2 integer argument, start and end
– Returns the substring that starts at position start and
ends before position end
– Example:
String str = “12345”;
System.out.println(str.substring(1,3);
//outputs 23
System.out.println(str.substring(0,4));
// outputs 1234
• Note that characters are numbered from zero!
substring() Method Cont’d
• Can call the substring method with one argument, start
• Returns the portion of the string that starts at position
start and continues to the end of the string.
String str=“uvwxyz”;
System.out.println(4); //prints yz
• Note once again that numbering starts at 0
– The character numbered 4 is actually the fifth character in the
string.
indexOf() Method
• indexOf searches a string for an occurrence of a
substring
• Takes an argument, a substring to search for
• Returns an integer
– The position of the substring in the string it is called on
– -1 if the substring is not found
– As always, numbering starts at zero
String st=“abcdefg”;
System.out.print(st.indexOf(“de”));
//prints 3
System.out.print(st.indexOf(“ed”));
//prints -1
compareTo() method
• Takes 1 parameter, a string str
• Returns an integer with the following sign:
– Positive if the string it is called on comes after str in
alphabetical order
– Negative if it comes before
– Zero if the strings are the same
• Example:
String str=“bbb”;
str.compareTo(“aaa”) will be positive.
str.compareTo(“ccc”) will be negative.
str.compareTo(“bbb”) will be zero.