ted all the String instance methods. We now discuss some of these instance
methods. One of them, length , returns the length, or number of characters, of
the string that the instance contains. For example, we have:
("abcd" + "ef").length()
Non-Java notation for strings
Often, we will be talking about a particular character of a string s or a
sequence of adjacent characters of s . It helps to have a notation for referring to
these parts of s :
s denotes the first character of s .
s denotes the second character of s .
s[s.length()-1] denotes the last character of s .
For example, if s is the string "abc" , then s is the character 'b' . Also, if int
variable i contains 0 , then s[i+2] is the character 'c' . Expression i of s[i] is
called the index of character number i . We stress that s[i] is not Java notation;
we use it because it helps us discuss strings. Also, when writing s[i] , we assume
that i lies in the range 0..s.length() - 1 .
A second non-Java notation describes a substring of a string :
is the string consisting of the characters s[h] , s[h + 1] , …, s[k] . The length of
s[h..k] is k+1-h . Here are examples, assuming that s is "abcded" :
s[2..4] is "cde"; it has length 4+1-2 = 3
s[2..3] is "cd"; it has length 3+1-2 = 2
s[2..2] is "c"; it has length 2+1-2 = 1
s[2..1] is ""; it has length 1+1-2 = 0
The last line above uses the convention that if the first index (2 in this case)
is one more than the second index (1), then the substring is the empty string. The
abbreviation s[h..] refers to the substring s[h..s.length()-1] .
Referencing the characters of a String
Function charAt retrieves a character from a string. The call s.charAt(i)
evaluates to the character s[i] . Thus, "At peace".charAt(1) is 't' . In refer-
ence s.charAt(i) , i is the index of the character in s .
Here is a specification of instance function charAt :
/** = this[i]. Precondition: 0 <= i < this.length */
public char charAt( int i)