目前,我想要做,做以下的方法:如果元素包含空格,创建更长的数组? (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