将数组值移动到左侧java

时间:2016-02-23 16:34:49

标签: java arrays loops for-loop

这是我在同一方法上的第二篇文章。该方法的描述如下:

“将2个或更多空格的所有序列减少到1个空格  字符数组。如果删除任何空格,则相同的数字  空字符'\ u0000'将填充结尾处的元素  阵“。

该方法的参数是char数组。我已经成功计算了重复空格的数量,但是,我不能为我的生活找出如何在考虑这样的重复空间的同时降低值。最后,该方法应该用'\ u0000'字符替换重复空格的索引数。这就是我到目前为止所做的:

// Calculate duplicate count before changing the array
    int duplicateCount = 0;
    for(int i = 0; i + 1 < characters.length; i++){
        if(characters[i] == ' ' && characters[i + 1] == ' '){
            duplicateCount++;
        }
    }

    // Shift the array down however much is needed
    for(int j = 0; j + 1 < characters.length; j++){
        if(characters[j] == ' ' && characters[j + 1] == ' '){
            for(int a = j, b = a + 1; b < characters.length; a++, b++){
                characters[a] = characters[b];
            }
        }
    }
    for(int replace = characters.length - duplicateCount; replace < characters.length; replace++){
        characters[replace] = '\u0000';
    }
}

因此,如果输入为:char [] characters = {'a', 't', ' ', '.', ' ', ' ', 'g', ' ', ' ', 'h', ' '};

输出应为:char [] expectedResult = {'a', 't', ' ', '.', ' ', 'g', ' ', 'h', ' ','\u0000', '\u0000'};

谢谢大家,这个问题好像应该这么简单但我卡住了。如果您能对您的答案提供任何解释,我将非常感激。 再次感谢你。

4 个答案:

答案 0 :(得分:2)

这很容易做到。只需遍历数组,跟踪你正在检查的索引(看看它是否是一个额外的空格)和你要复制的索引。最后,用'\ u0000'值填充数组,然后就完成了。

我把它变成了一个简单的状态机,可以很容易地跟踪我们是否有额外的空格。

public void squeezeMe(char[] characters) {
    SqueezeState state = SqueezeState.START;

    int p = 0;
    for (int i = 0; i < characters.length; i++) {
        SqueezeState newState = SqueezeState.START;

        // Evaluate input based on current state
        switch (state) {
        case START:
        case NOT_A_SPACE: {
            if (Character.isWhitespace(characters[i])) {
                newState = SqueezeState.FIRST_SPACE;
            } else {
                newState = SqueezeState.NOT_A_SPACE;
            }
            break;
        }
        case FIRST_SPACE:
        case EXTRA_SPACE: {
            if (Character.isWhitespace(characters[i])) {
                newState = SqueezeState.EXTRA_SPACE;
            } else {
                newState = SqueezeState.NOT_A_SPACE;
            }
        }
        }

        // Transition to new state
        switch (newState) {
        case NOT_A_SPACE:
        case FIRST_SPACE: {
            if (i > p) {
            characters[p] = characters[i];
            }
            p++;
            break;
        }
        }

        state = newState;
    }

    for (int i = p; i < characters.length; i++) {
        characters[i] = '\u0000';
    }

}

private enum SqueezeState {
    START, NOT_A_SPACE, FIRST_SPACE, EXTRA_SPACE;
}

@Test
public void test1() {
    char[] result = { 'a', 't', ' ', '.', ' ', ' ', 'g', ' ', ' ', 'h', ' ' };
    char[] expected = { 'a', 't', ' ', '.', ' ', 'g', ' ', 'h', ' ', '\u0000', '\u0000' };
    squeezeMe(result);
    assertEquals(expected.length, result.length);
    for (int i = 0; i < expected.length; i++) {
        assertEquals("Index " + i, expected[i], result[i]);
    }
}

如果你不想使用状态机,你可以这样做:

public void squeezeMe(char[] characters) {
    boolean copyThis = false;
    boolean wasLastASpace = false;

    int p = 0;
    for (int i = 0; i < characters.length; i++) {
        if (Character.isWhitespace(characters[i])) {
            copyThis = !wasLastASpace;
            wasLastASpace = true;
        } else {
            copyThis = true;
            wasLastASpace = false;
        }

        if (copyThis) {
            if (i != p) {
                characters[p] = characters[i];
            }
            p++;
        }
    }

    for (int i = p; i < characters.length; i++) {
        characters[i] = '\u0000';
    }
}

答案 1 :(得分:1)

你可以在一次通过数组中复制它,使用两个整数指针来输入&#34;输入&#34;和&#34;输出&#34;,分别作为输入和输出数组的索引。

char[] output = new char[input.length];
output[0] = input[0];  // Copy the first character, it's not a repeated space.
int ip = 1;
int op = 1;
while (ip < input.length) {
  if (input[ip] != ' ' || input[ip - 1] != ' ') {
    output[op++] = input[ip++];
  } else {
    ip++;
  }
}
while (op < output.length) {
  output[op++] = '\0';
}

答案 2 :(得分:0)

我猜这是你的功课,你不应该使用任何图书馆等。这是我使用正则表达式的解决方案。

import java.util.Arrays;
import java.util.regex.Pattern;
public class ReplaceMultipleWhiteSpace(){
public static void main(String[] args){
    char[] array = new char[]{'a', ' ', ' ', ' ', ' ', ' ', 'b', ' ', 'c'};
    String s = new String(array);
    int length = s.length();
    Pattern twoOrMoreWhiteSpace = Pattern.compile("( {2,})");
    String replaced = twoOrMoreWhiteSpace.matcher(s).replaceAll(" ");
    int diff = length - replaced.length();
    char[] charArray = replaced.toCharArray();
    char[] finalArray = Arrays.copyOf(charArray, replaced.length() + diff);
    for (int i = replaced.length(); i < finalArray.length; i++) {
        finalArray[i] = '\u0000';
    }
    System.out.println(Arrays.toString(array));
    System.out.println(Arrays.toString(finalArray));
}
} 

答案 3 :(得分:0)

下面的代码应该非常明显。您不需要计算最后需要填写的字符数 - 只需填写符合条件的字符(=前一个和当前字符不是''),如果不符合标准,请填写复制它。最后,只需填充数组的剩余部分。

server {
    listen 443 ssl;

    ssl_certificate /etc/nginx/ssl/public.crt;
    ssl_certificate_key /etc/nginx/ssl/private.rsa;

    ssl_client_certificate /etc/nginx/ssl/client_ca.pem;
    ssl_verify_client on;

    server_name api.my_domain.com;

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass http://app/api;
    }
}