Programming and Problem Solving with Java

(やまだぃちぅ) #1
3.8 Additional String Operations | 127

then the statement


position = phrase.indexOf("the");


assigns to positionthe value 12. In contrast, the statement


position = phrase.indexOf("rat");


assigns to positionthe value 1, because no match was found.
The argument to the indexOfmethod can also be a charvalue. In this case,indexOfsearches
for the first occurrence of that character within the string and returns its position (or –1, if
the character was not found). For example, the code segment


String theString;


theString = "Abracadabra";
position = theString.indexOf('a');


assigns the value 3 to position, which is the position of the first occurrence of a lowercase a
in theString.
Following are more examples of calls to the indexOfmethod, assuming the following
code segment has been executed:


String str1;
String str2;


str1 = "Programming and Problem Solving";
str2 = "gram";


Method Call Value Returned by Method
str1.indexOf("and") 12
str1.indexOf("Programming") 0
str2.indexOf("and")  1
str1.indexOf("Pro") 0
str1.indexOf("ro"+ str2) 1
str1.indexOf("Pr"+ str2)  1
str1.indexOf(' ') 11

In the fourth example,str1contains two copies of the substring "Pro", but indexOfreturns
only the position of the first copy. Also notice that the matches can be either separate words
or parts of words—indexOfmerely tries to match the sequence of characters given in the ar-
gument list. The final example demonstrates that the argument can be as simple as a sin-
gle character, even a single blank.

Free download pdf