[英]Remove chars from a String in Java
I have a String and I need to remove a certain char from it and I have been able to do this, but I still have a problem. 我有一个字符串,我需要从中删除某个字符,我已经能够做到这一点,但是仍然有问题。 I get rid of the char, but the length of the string stays the same. 我摆脱了char,但是字符串的长度保持不变。
public class HelloWorld{
public static void main(String []args){
String data = "Hello World";
System.out.println(data);
System.out.println("string length: " + data.length());
char letter = 'l';
data = data.replace(letter, '\0');
System.out.println(data);
System.out.println("string length: " + data.length());
}
}
This gives me the output: 这给了我输出:
Hello World
string length: 11
Heo Word
string length: 11
I need it to be: 我需要它是:
Hello World
string length: 11
Heo Word
string length: 8
Why does it seem to be counting chars that are no longer in the string? 为什么似乎要计算字符串中不再存在的字符?
This replace
is not right: 此replace
不正确:
data = data.replace(letter, '\\0');
Java doesn't treat null characters specially. Java不会特别对待空字符。 Instead, use: 而是使用:
data = data.replace(String.valueOf(letter), "");
This is because there are two overloads, neither of which is replace(char, CharSequence)
. 这是因为有两个重载,都不是replace(char, CharSequence)
。 We therefore use the replace(CharSequence, CharSequence)
overload (as Strings are CharSequence
s) 因此,我们使用replace(CharSequence, CharSequence)
重载(因为String是CharSequence
)
If you're OK with redefining letter
to be a String, you can simply do: 如果可以将letter
重新定义为字符串,可以执行以下操作:
data = data.replace(letter, "");
You did not remove chars, just replace them. 您没有删除字符,只需替换它们。
Try this: 尝试这个:
String letter = "l";
data = data.replace(letter, "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.