Write a program that will take a sentence (a single String), picks out the indiv
ID: 3831306 • Letter: W
Question
Write a program that will take a sentence (a single String), picks out the individual words (substrings), and puts each of them into a String array. Ex. input: "the lazy dog" output:the
lazy
dog
keep in mind that I am a beginner, so don't make it to difficult for me to undesrstand please. The teacher also said to use indexOf. Also remember to put every individual word into an array before it is spit back out. I've asked this same question twice already and it hasn't been put into an array, so please don't forget to do that. It is the whole point of the problem.
Explanation / Answer
Below is your code: -
StringTester.java
public class StringTester {
public static void main(String[] args) {
String line = "the lazy dog";// initializing the string.
int spaceCount = 0; // number of spaces in text
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == ' ' && i != line.length() - 1) {
// checking if character encountered is space and character at
// index is not last character
spaceCount++;
}
}
String[] strArr = new String[spaceCount + 1]; // initializing array with
// number of elements
// equal to number of
// words
String word = line.substring(0, line.indexOf(" ")); // getting first
// word from line
// and saving to
// word
int count = 0;
while (!word.isEmpty()) {
strArr[count++] = word;// inserting word to string array and
// incrementing the counter
line = line.substring(line.indexOf(" ") + 1) + " "; // deleting
// first word
// form line
word = line.substring(0, line.indexOf(" "));// getting next word
// from line
}
for (int i = 0; i < strArr.length; i++) {
System.out.println(strArr[i]);// printing array
}
}
}
Sample Run: -
the
lazy
dog
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.