Java Reference
In-Depth Information
5.2.6
Exercises on strings
E1. Write (and test in your IDE —test all your work) an expression to produce a
String that contains, in order, these things: "variable d: " , the value of
expression d , and " . "
E2. Write an expression to produce a String that contains: the value of variable
firstName , ", " , and the value of variable lastName .
E3. Write an expression to produce a String that, when printed, will occupy two
lines. The first line should contain "Tuesday, November " , and the value of
variable day . The second line should contain three blanks followed by the value
of variable weather (e.g. "cloudy" or "rainy" . Hint: use a new-line character.
E4. Write an expression to produce a String that, when printed, will occupy two
lines. The first line should contain "CS100, computers and programming"; the
second line, "instructor: " followed by the value of variable instructor .
E5. Write a function that, given a String s , returns the number of characters
before the first period '.' in s . If there is no period, it should return the length
of s . E.g. if s is "Gries. D." , the answer is 5 ; if s is "Gries, D" , the answer
is 8 . Do not use a loop.
/** Remove leading and trailing spaces from q and extract and return the unsigned int that
remains. q must begin with an unsigned integer, preceded by 0 or more blanks and ended
by either 1 or more blanks or the end of the string. Example: if q is " 45 32" , change
q to " 32" and return 45 . */
public static int extractInt(StringBuffer q) {
// Remove beginning blanks from q
int i= 0;
while (q.charAt(i) == ' ') {
i= i + 1;
}
q.delete(0, i);
// Find the index i-1 of the last character of the unsigned integer
i= 0;
while (i != q.length() && q.charAt(i) != ' ') {
i= i + 1;
}
int v= Integer.parseInt(q.substring(0, i));
q.delete(0, i);
return v;
}
Figure 5.2:
Function extractInt
Search WWH ::




Custom Search