【发布时间】:2016-06-04 18:19:45
【问题描述】:
我正在尝试创建一个方法,该方法将采用一个 char 数组,删除所有重复的空格(2 个或更多),然后将 '\u0000' 字符放在末尾,因为删除了许多空格以便数组长度很满意。我意识到我必须将元素向下移动,但这是我遇到麻烦的地方。我的程序在 2 个空格的情况下运行良好,但连续三个空格会使它失效。我理解为什么会发生这种情况,但我不知道如何解决它。我知道它源于代码characters[j] = characters[j+1],但我不知道如何修复它。
int duplicateCount = 0;
// Create a loop to read the element values
for(int i = 0; i + 1 < characters.length; i++){
// If the element is a space and the next one is a space
if(characters[i] == ' ' && characters[i+1] == ' '){
// Add to duplicate count and start shifting values down
duplicateCount++;
// *THIS IS WHERE I THINK BUG IS*
for(int j = i; j < characters.length - 1; j++){
characters[j] = characters[j+1];
}
}
}
// Replace characters at end with how many duplicates were found
for(int replace = characters.length - duplicateCount; replace < characters.length; replace++){
characters[replace] = '\u0000';
}
}
谢谢大家。
【问题讨论】:
-
这对字符有效吗?最重要的是,数组?它似乎只适用于字符串
-
您希望将所有空格移到末尾。对吗?
-
正确,所有空格都将作为 \u0000 个字符出现在末尾span>
-
您的问题解决了吗?