目前,我想要做,做以下的方法:如果元素包含空格,創建更長的數組? (JAVA)
- 需要3個字符串數組(也就是說,beforeList和afterList)
- 將查找在這兩個詞和詞beforeList,如果發現,與單詞替換afterList
- 返回一個新的數組,它本身
例如接通與afterList字符到新的元素的元素,這裏是一個測試的情況下,請注意,「我'm'分裂成兩個元素在最後一個陣列「我」和「上午」的最後一個排列:
String [] someWords = {"i'm", "cant", "recollect"};
String [] beforeList = {"dont", "cant", "wont", "recollect", "i'm"};
String [] afterList = {"don't", "can't", "won't", "remember", "i am"};
String [] result = Eliza.replacePairs(someWords, beforeList, afterList);
if (result != null && result[0].equals("i") && result[1].equals("am")
&& result[2].equals("can't") && result[3].equals("remember")) {
System.out.println("testReplacePairs 1 passed.");
} else {
System.out.println("testReplacePairs 1 failed.");
}
我最大的問題是在佔這種空白的情況。我知道我將在下面發佈的代碼是錯誤的,但是我一直在嘗試不同的方法。我認爲我現在的代碼應該返回一個空數組,它是第一個數組的長度,但佔空間。我意識到它可能需要一個完全不同的方法。任何建議,雖然將不勝感激,我會繼續嘗試並弄清楚,但如果有辦法做到這一點,那麼我很樂意聽到並從中吸取教訓!謝謝。
public static String[] replacePairs(String []words, String [] beforeList, String [] afterList) {
if(words == null || beforeList == null || afterList == null){
return null;
}
String[] returnArray;
int countofSpaces = 0;
/* Check if words in words array can be found in beforeList, here I use
a method I created "inList". If a word is found the index of it in
beforeList will be returned, if a word is not found, -1 is returned.
If a word is found, I set the word in words to the afterList value */
for(int i = 0; i < words.length; i++){
int listCheck = inList(words[i], beforeList);
if(listCheck != -1){
words[i] = afterList[listCheck];
}
}
// This is where I check for spaces (or attempt to)
for(int j = 0; j < words.length; j++){
if(words[j].contains(" ")){
countofSpaces++;
}
}
// Here I return an array that is the length of words + the space count)
returnArray = new String[words.length + countofSpaces];
return returnArray;
}
問題,「這裏的一些代碼,告訴我什麼錯誤「通常在StackOverflow上是無關緊要的。發佈前需要做一些基礎工作。首先,通過IDE調試器中的代碼來確定它的行爲不符合您的期望。然後詢問一個具體問題,描述你期望發生的事情,以及與實際發生的事情有什麼不同(即顯示預期的和實際的產出)。我_think_我明白你的問題與'我'需要佔用2個輸出陣列位置有關,但我不確定。 –
如果輸入包含連續超過1個空格的單詞,您是否必須考慮? – Maljam
對不起,如果我不清楚,我可以盡我所能編輯帖子。不,我相信它只是在兩個空白之間,然後刪除空格,並在新數組中創建兩個獨立的數組元素。 – dj1121