简体   繁体   中英

Java: How can i remove null value from a string?

When this code is run, it outputs 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", "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM