SLaks is recommending in his comment you to use the substring()
method. Checking the API documentation for String
:
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
. Thus the length of the substring is endIndex-beginIndex
.
Examples:
"hamburger".substring(4, 8)
returns "urge"
"smiles".substring(1, 5)
returns "mile"
So, consider this:
public static void displayWords(String line) {
while(line.length() > 0) { // This is the first part (the obvious one)
/*
You should do something here that tracks the index of the first space
character in the line. I suggest you check the `charAt()` method, and use
a for() loop.
Let's say you find a space at index i
*/
System.out.println(line.substring(0,i)); // This prints the substring of line
// that goes from the beginning
// (index 0) to the position right
// before the space
/*
Finally, here you should assign a new value to line, that value must start
after the recently found space and end at the end of the line.
Hint: use substring() again, and remember that line.lengh() will give you
the position of the last character of line plus one.
*/
}
}
You've had enough time... and I'm feeling generous tonight. So here is the solution:
public static void displayWords(String line) {
int i; // You'll need this
while(line.length() > 0) { // This is the first part (the obvious one)
/*
Here, check each character and if you find a space, break the loop
*/
for(i = 0; i < line.length(); i++) {
if(line.charAt(i) == ' ') // If the character at index i is a space ...
break; // ... break the for loop
}
System.out.println(line.substring(0,i)); // This prints the substring of line
// that goes from the beginning
// (index 0) to the position right
// before the space
/*
Here, the new value of line is the substring from the position of the space
plus one to the end of the line. If i is greater than the length of the line
then you're done.
*/
if(i < line.length())
line = line.substring(i + 1, line.length());
else
line = "";
}
}
After reading your question again, I realised that it should be a recursive solution... so here is the recursive approach:
public static void displayWords(String line) {
int i;
for(i = 0; i < line.lengh(); i++) {
if(line.charAt(i) = ' ')
break;
}
System.out.println(line.substring(0, i);
if(i < line.lengh())
line = line.substring(i + 1, line.lengh();
else
line = "";
if(line.lengh() > 0)
displayWords(line);
}