Java中字符串字符的结尾

2022-01-12 00:00:00 arrays char java

我正在解决一个简单的问题:

I was solving an easy question :

在Java中删除字符数组的某些字符,想法很简单:

Remove certain characters of a character array in Java , the idea is straightforward :

static void remove_char(char[] arr, char c){
    int r = 0;
    for (int i = 0 ; i < arr.length ; i++){
        if (arr[i] == c){
            r++;
            continue;
        }
        arr[i - r] = arr[i];
    }
    arr[arr.length - r] = ''; // ??
    return;
}

我想放置一个 结束字符,它表示当我们想要生成字符串时不必考虑数组的其余部分,例如,使用 new String(arr)

I want to put an ending character which signals that the rest of the array doesn't have to be considered when we want to, for example, generate a string using new String(arr)

Java 中有这样的字符吗?(我猜在 C 中是 但我不确定)

Is there any such character in Java ? ( I guess in C it's but I am not sure)

例如当我们调用:

System.out.println(new String(remove_char(new char[] {'s','a','l','a','m'} ,'a')))

这将被打印出来:slm m

虽然我想获得 slm 并且我想 in-place 不使用新数组

While I want to get slm and I want to do this in-place not using a new array

推荐答案

Java 不像 C 那样标记"字符串的结尾.它跟踪长度和值,因此字符串中可能包含零字符 ().如果您从包含 字符的 char 数组创建 String,则生成的 String 将包含这些字符.

Java doesn't "mark" the end-of-string as C does. It tracks length & values, so it's possible to have zero-chars () in the string. If you create a String from a char array containing chars, the resultant String will contain those characters.

另请注意,数组具有静态大小 - 它不能重新调整大小,因此您必须自己跟踪大小"(String 构造函数不会从 char 末尾为您删除不需要的字符数组).

Note also, an array has a static size - it cannot be re-sized, so you'll have to track the "size" yourself (the String constructor won't drop undesirable characters for you from the end of a char array).

考虑使用任一:

  • Clyde Byrd III 建议的 StringBuilder,或

String(char value[], int offset, int count);您必须以编程方式确定 offsetcount 的适当值.也许字符串方法,例如 replaceconcatsubstring 可能会有所帮助.

String(char value[], int offset, int count); you'll have to determine programmatically what the appropriate values for offset and count would be. Perhaps String methods, such as replace, concat, or substring might help.

相关文章