Saturday, 18 August 2007

Operators and Assignments (Part 11)

Strings - cont

Extracting Substrings
The String class includes a method, substring(), that will extract a substring from a string. There are two versions of this. The first one,

public String substring(int beginIndex)

returns a new string that is a substring of this string., the substring begins with the character at the specified index and extends to the end of this string. The second one,

public String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. For example,

"smiles".substring(1, 5) returns "mile"

Exercise 3 – 5
For this exercise you are required to segment the following string:
“We Love our Java Course”
and display it as follows:

We
Love
our
Java
Course

You should make use of both indexOf() and substring() methods. Use the online documentation to help with this exercise. Although we won’t cover loops until later in this section, you may need to use a While loop. This has the syntax of :

while (condition is true) {
// CodeText that needs to iterate goes here
}

No comments:

Post a Comment