[英]I have to realize a method findWord, that finds index of word in a text and then adds it into int array, Someone can help me?
public int[] findWord(String text, String word) throws NullPointerException {
// my code must be here
return ;
}
}
要獲取文本中單詞的索引:
text.indexOf(word);
您可以將此值添加到數組中
public int[] findWord(String text, String word) throws NullPointerException
{
int[] first = new int[text.length()];
int j=0;
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1;) {
System.out.println(i);
}
return first;
}
這是我的嘗試,如何將 (i) 添加到我的數組中? 它只是打印完全需要的數字。
創建ArrayList<Integer> arrayList = new ArrayList<>();
,然后通過方法arrayList.add(int element)
添加元素,然后將 AL 轉換為數組: int[] result = arrayList.toArray(new int[arrayList.size()]);
add() - 將元素添加到 ArrayList 的末尾
我做到了!
public int[] findWord(String text, String word) 拋出 NullPointerException {
int[] first = new int[text.length()];
int j=0;
for (int i = -1; (i = text.indexOf(word, i + 1)) != -1;j++) {
first[j]=i;
}
int[] second = new int[j];
second = Arrays.copyOf(first,j);
return second;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.