Java中字符串字符的结尾

End of string character in Java(Java中字符串字符的结尾)
本文介绍了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.

这篇关于Java中字符串字符的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)