Je crois que ce serait faire ce que vous voulez:
import java.util.*;
public class Test {
public static List<String> ngrams(int n, String str) {
List<String> ngrams = new ArrayList<String>();
String[] words = str.split(" ");
for (int i = 0; i < words.length - n + 1; i++)
ngrams.add(concat(words, i, i+n));
return ngrams;
}
public static String concat(String[] words, int start, int end) {
StringBuilder sb = new StringBuilder();
for (int i = start; i < end; i++)
sb.append((i > start ? " " : "") + words[i]);
return sb.toString();
}
public static void main(String[] args) {
for (int n = 1; n <= 3; n++) {
for (String ngram : ngrams(n, "This is my car."))
System.out.println(ngram);
System.out.println();
}
}
}
Sortie:
This
is
my
car.
This is
is my
my car.
This is my
is my car.
solution Une "sur demande" mis en œuvre comme Iterator:
class NgramIterator implements Iterator<String> {
String[] words;
int pos = 0, n;
public NgramIterator(int n, String str) {
this.n = n;
words = str.split(" ");
}
public boolean hasNext() {
return pos < words.length - n + 1;
}
public String next() {
StringBuilder sb = new StringBuilder();
for (int i = pos; i < pos + n; i++)
sb.append((i > pos ? " " : "") + words[i]);
pos++;
return sb.toString();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
'ngrams (« Ceci est ma voiture », -3)' (désolé, pas pu résister) – wds
'ngrams (" Ceci est mon voiture ", -3)' fonctionne bien. 'ngrams (" Ceci est ma voiture ", 6)' aboutit à une exception 'NegativeArraySizeException'. – aioobe
Qu'attendez-vous dans ces cas? Je suggère de mettre un test au début de la méthode et retourner un tableau vide. En général, je vois peu de réponses SO avec une gestion d'erreur sophistiquée. – Landei