String Processing in
Java
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()
Calling Methods on Strings
• Methods on strings are instance methods
– Instance of String, followed by
– a period
– followed by the method name
– followed by the parameter list in parentheses
• E.g.
– [Link](3,4);
– myString above must be declared as a string.
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”;
[Link](“abc”) // Evaluates to true
[Link](“xyz”) // Evaluates to false
• Don’t compare strings using ==
– E.g. if (mystring==yourstring)…
– Java will let you, but it won’t do what you expect
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”;
[Link]([Link]());//5
[Link]([Link]());//4
substring() Method
• Used to get a portion of an existing string
• Can have 2 integer arguments, start and end
– Returns the substring that starts at position start and
ends before position end
– Example:
String str = “ABCDE”;
[Link]([Link](1,3);
//outputs BC
[Link]([Link](0,4));
// outputs ABCD
• 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”;
[Link]([Link](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”;
[Link]([Link](“de”));
//prints 3
[Link]([Link](“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 x=“bbb”;
[Link](“aaa”) will be positive.
[Link](“ccc”) will be negative.
[Link](“bbb”) will be zero.