As Scary Wombat suggested in the comments, in the beginning of the method, you can create an ArrayList. Then within in each loop iteration, you can just keep adding to it. At the end of the method, you can convert the list to an array using the toArray method.
import java.util.ArrayList;
import java.util.List;
class Example {
public static String[] findWordsOfLength(String letters, int wordSize) {
if(letters == null) {
return null;
}
int size = letters.length();
int wordMax = size - wordSize + 1;
if(size < wordMax || wordMax <= 0) {
return new String[0];
}
List<String> result = new ArrayList<>();
for (int i = 0; i < wordMax; i++) {
result.add(letters.substring(i, i + wordSize));
}
return result.toArray(new String[0]);
}
public static void main(String[] args) {
String[] word = findWordsOfLength("fourgooddogsswam", 4);
for(String word : words) {
System.out.println(word);
}
/**
* Output in console:
*
* four
* ourg
* urgo
* rgoo
* good
* oodd
* oddo
* ddog
* dogs
* ogss
* gssw
* sswa
* swam
*/
}
}
Note that the advantage of using a list is that you don't need to know its size in advance. An array, on other hand, is initialized with a set size.
If you must use an array, you could do:
public static String[] findWordsOfLength(String letters, int wordSize) {
if(letters == null) {
return null;
}
int size = letters.length();
int wordMax = size - wordSize + 1;
if(size < wordMax || wordMax <= 0) {
return new String[0];
}
int j = 0;
String[] result = new String[wordMax];
for (int i = 0; i < wordMax; i++) {
result[j ++] = letters.substring(i, i + wordSize);
}
return result;
}