在Java中的字符串字符结束 [英] End of string character in 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] = '\0'; // ??
return;
}
我想把这标志着该阵列的其余部分并没有被认为是当我们想,例如,使用生成的字符串的结束字符
新的String(ARR)
有没有在Java中任何这样的字符? (我猜 C
是 \\ 0
,但我不知道)
Is there any such character in Java ? ( I guess in C
it's \0
but I am not sure)
例如,当我们致电:
的System.out.println(新的String(remove_char(新的char [] {'S','A','L','A','M'},'A') ))
这将打印: SLM米
虽然我想获得 SLM
,我想这样做原位
不使用新的数组
While I want to get slm
and I want to do this in-place
not using a new array
推荐答案
Java不标记的结束串为C一样。它跟踪长度放大器;值,因此它可能具有零字符字符串中( \\ 0
)。如果您创建一个字符串
从包含字符数组 \\ 0
字符,得到的字符串
将包含这些字符。
Java doesn't "mark" the end-of-string as C does. It tracks length & values, so it's possible to have zero-chars (\0
) in the string. If you create a String
from a char array containing \0
chars, the resultant String
will contain those characters.
还请注意,数组有一个静态的大小 - 它不能被重新大小,所以你必须追踪大小自己(String构造将不会从一个字符的结束下降不良分子为你阵列)。
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).
考虑使用可以:
-
A
的StringBuilder
由克莱德·伯德III建议,或
A
StringBuilder
as suggested by Clyde Byrd III, or
字符串(char值[],诠释抵消,诠释计数)
;你必须决定编程什么相应的值偏移
和计数
会。或许字符串的方法,如替换
, CONCAT
或串
可能的帮助。
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中的字符串字符结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!