[英]Java: How can i remove null value from a string?
When this code is run, it outputs nullhi
. 运行此代码时,将输出
nullhi
。 Why is it doing this? 为什么这样做呢?
public static void main(String[] args) {
String[] a = new String[1];
String m = null;
String c = "hi";
for (int i = 0 ; i < c.length() ; i++){
a[0] = a[0] + c.charAt(i);
}
System.out.print(a[0]);
}
Before the loop, write: 在循环之前,编写:
a[0] = "";
ie 即
public static void main(String[] args) {
String[] a= new String[1];
String m = null;
String c = "hi";
a[0] = "";
for (int i=0 ; i<c.length() ; i++){
a[0]=a[0]+c.charAt(i);
}
System.out.print(a[0]);
}
Do this 做这个
for (int i=0 ; i<c.length() ; i++){
a[i] = "";
a[i]= c.charAt(i);
}
what you are doing is 你在做什么
for (int i=0 ; i<c.length() ; i++){
a[0]=a[0]+c.charAt(i); // a[0] is null,
}
测试字符串是否为空
a[0] = ((a[0] == null) ? "" : a[0] ) + c.charAt(i);
您需要替换“ null”,因此代码的最后一行应为
System.out.println(a[0].replace("null", "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.