I have a task in where I am instructed to create a method that returns words from a string based on a given length. The specific instructions are as follows:
This method will input a sentence with multiple words separated by spaces. The input number represents the size of the word we are looking for. Return a string array with all words found with the input size
Example:
String s = “Monday is a new day”;
int n = 3; //3 letter words
howManyWord(s, n) returns {“new”, “day”}
howManyWord(s, 2) returns {“is”}.
So far, this is my take at the solution. The main issue I am having is in the second for loop in terms of assigning words to the array itself
public String[] howManyWord(String s, int n) {
//count the amount of words in the String
int counter1 = 0;
for(int a1 = 1; a1 < s.length(); a1++) {
char c1 = s.charAt(a1-1);
char c2 = s.charAt(a1);
if(c1 != ' ' && c2 == ' '){
counter1++;
}
}
counter1 += 1;
//Get the words of a string into an array + the loop in question
String[] words = new String[counter1];
String[] output = new String[counter1];
for(int a2 = 1; a2 < s.length(); a2++) {
char c1 = s.charAt(a2-1);
char c2 = s.charAt(a2);
int counter2 = 0;
if(c1 != ' ' && c2 == ' '){
int index1 = s.indexOf(c1);
int index2 = s.indexOf(c2);
words[counter2] = s.substring(index1, index2);
counter2++;
}
}
//assign words of a specific length into output array
for(int a3 = 0; a3 < output.length; a3++) {
if(words[a3].length() == n){
output[a3] = words[a3];
}
}
return output;
}
How would I go about this issue? Thanks!
String[] worlds = s.split(" ")and just checking the lengths?