Java Reference
In-Depth Information
EXAMPLE 3-3
Consider the following statements:
String sentence;
String str1;
String str2;
String str3;
String str4;
sentence = "It is sunny and warm.";
str1 = "warm.";
str2 = "Programming with Java";
str3 = "sunny";
str4 = "Learning Java Programming is exciting";
The following statements show how String methods startsWith , endsWith , and
regionMatches work.
Expression
Effect
sentence.startsWith("It")
Returns true
sentence.startsWith(str1)
Returns false
sentence.endsWith("hot")
Returns false
sentence.endsWith(str1)
Returns true
sentence.regionMatches(6, str3, 0, 5)
Returns true
sentence.regionMatches( true , 6, "Sunny", 0, 5)
Returns true
str4.regionMatches(9, str2, 17, 4)
Returns true
For the most part, the statements are straightforward. Let's look at the last three state-
ments, which use the method regionMatches :
sentence.regionMatches(6, str3, 0, 5)
In this statement, we want to determine whether str3 appears as a substring in the string
sentence starting at position 6 . Notice that the last three arguments, str3 , 0 , and 5 ,
specify that in str3 the starting index is 0 and the length of the substring is 5 . The
substring in sentence starting at position 6 and of length 5 matches str3 . So this
expression returns true .
The expression:
sentence.regionMatches( true , 6, "Sunny", 0, 5)
is similar to the previous expression, except that when the substrings are compared, the
case is ignored, that is, uppercase and lowercase letters are considered the same. Next, let's
look at the expression:
str4.regionMatches(9, str2, 17, 4)
 
Search WWH ::




Custom Search