[英]How to remove 2 or more spaces that are next to each other from a char array
public static void removeDuplicateSpaces(char[] characters) {
int dupCount = 0;
for (int i = 0; i < characters.length; i++) {
if (characters[i] == ' ' && characters[i + 1] == ' ') {
dupCount++;
for (int j = i; j < characters.length - 1; j++) {
characters[j] = characters[j + 1];
}
if ((characters[i] == ' ' && characters[i + 1] == ' ')) {
dupCount++;
for (int j = i; j < characters.length - 1; j++) {
characters[j] = characters[j + 1];
}
dupCount++;
}
for (int add = characters.length - 1; add >
characters.length- dupCount; add--) {
characters[add] = '\u0000';
}
}
}
}
I need to reduce all sequences of 2 or more spaces to 1 space within the characters array. 我需要将所有2个或更多空格的序列减少到characters数组中的1个空格。 If any spaces are removed then the same number of Null character '\ ' will fill the elements at the end of the array.
如果删除了任何空格,则相同数量的Null字符'\\ u0000'将填充数组末尾的元素。 My code does not remove 4 spaces when there are 5 spaces in between.
当两者之间有5个空格时,我的代码不会删除4个空格。 Such as {'e','','','','','','4'}
如{'e','','','','','','4'}
How about converting it to String
, doing some regex and back to char array? 如何将其转换为
String
,做一些正则表达式然后返回char数组?
new String(characters).replaceAll("[ ]+", " ").toCharArray()
EDIT: Ok, I see you're actually not returning the array, but modifying the original array. 编辑:好的,我看到您实际上不是在返回数组,而是在修改原始数组。 Then you could use a simple loop
然后您可以使用一个简单的循环
String s = new String(characters).replaceAll("[ ]+", " ");
for (int i = 0; i < characters.length; i++) {
characters[i] = (i < s.length() ? s.charAt(i) : '\u0000');
}
different variant, to show you how it should work with simple loops: 不同的变体,向您展示如何使用简单的循环:
public static void removeDuplicateSpaces(final char[] characters) {
for (int i = 0; i < characters.length; i++) {
while (characters[i] == ' ') { // while current symbol is space
for (int j = (i + 1); j < characters.length; j++)
characters[j - 1] = characters[j]; // shift the rest of array
characters[characters.length - 1] = 0;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.