String
String
String
Implementing strings as built-in objects
allows Java to provide a full complement of
features that make string handling convenient.
Program3:
startsWith( ) and endsWith( )
boolean startsWith(String str)
boolean endsWith(String str)
For example,
"Foobar".endsWith("bar")
"Foobar".startsWith("Foo")
are both true.
"Foobar".startsWith("bar", 3) TRUE
compareTo( )
• int compareTo(String str)
if(s1.compareTo(s2))
Searching Strings
• indexOf( ) Searches for the first occurrence of a
character or substring.
• lastIndexOf( ) Searches for the last occurrence of
a character or substring
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
Program 4
• substring( )
• The first is String substring(int startIndex)
• The second form of substring( ) allows you to
specify both the beginning and ending index
of the substring:
• String substring(int startIndex, int endIndex)
• Program 5:
concat( )
• String concat(String str)
• String s1 = "one";
• String s2 = s1.concat("two");
trim( )
• Method returns a copy of the invoking string
from which any leading and trailing
whitespace has been removed. It has this
general form: String trim( )
• Here is an example:
• String s = " Hello World ".trim();