Java:如何从字符串中删除空值?

时间:2021-09-10 06:25:05

When this code is run, it outputs nullhi. Why is it doing this?

运行此代码时,它输出nullhi。它为什么这样做?

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]);
}

4 个解决方案

#1


4  

Before the loop, write:

在循环之前,写:

a[0] = "";

i.e.

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]);

}

#2


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, 
}

#3


-1  

Test if string is null

测试string是否为null

a[0] = ((a[0] == null) ? "" : a[0] ) + c.charAt(i);

#4


-1  

You'll need to replace "null", so the last line of your code should be

您需要替换“null”,因此代码的最后一行应该是

System.out.println(a[0].replace("null", "");

#1


4  

Before the loop, write:

在循环之前,写:

a[0] = "";

i.e.

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]);

}

#2


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, 
}

#3


-1  

Test if string is null

测试string是否为null

a[0] = ((a[0] == null) ? "" : a[0] ) + c.charAt(i);

#4


-1  

You'll need to replace "null", so the last line of your code should be

您需要替换“null”,因此代码的最后一行应该是

System.out.println(a[0].replace("null", "");