Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^126) | Arithmetic Expressions


3.8 Additional String Operations


Now that we have introduced numeric types, we can take advantage of additional features
of the Stringdata type. Here we introduce three useful methods that operate on strings:
length,indexOf, and substring. All three are value-returning instance methods.

The lengthMethod


Thelengthmethod, when applied to aString, returns anintvalue that equals the number of
characters in the string. IfmyNameis aStringobject, a call to thelengthmethod looks like this:

myName.length()

The lengthmethod requires no arguments to be passed to it, but you still must use paren-
theses to signify an empty argument list. Also,lengthis a value-returning method, so the
method call must appear within an expression:

String firstName; // Local declarations
String fullName;
int len;

firstName = "Alexandra";
len = firstName.length(); // Assigns 9 to len
fullName = firstName + " Jones";
len = fullName.length(); // Assigns 15 to len

The indexOf Method


TheindexOfmethod searches a string to find the first occurrence of a particular substring and
returns anintvalue indicating the point where the substring was found.The substring, passed
as an argument to the method, can be a literal string or aStringexpression. Ifstr1andstr2
are of typeString, the following are valid method calls, each of which returns an integer:

str1.indexOf("the") str1.indexOf(str2) str1.indexOf(str2 + "abc")

In each case,str1is searched to see if the specified substring appears within it. If so, the
method returns the position in str1where the match begins. (Positions are numbered start-
ing at 0, so the first character in a string is in position 0, the second is in position 1, and so
on.) For a successful search, the match must be exact, including identical capitalization. If
the substring could not be found, the method returns the value 1.
Given the code segment

String phrase;
int position;

phrase = "The dog and the cat";
Free download pdf