我在将字符数组转换为Java字符串时遇到问题。我只想复制非空的字符。拿这个代码,例如:将字符数组转换为无空格的字符串
import java.util.*;
import java.lang.*;
import java.io.*;
class CharArrayToStringTest
{
public static void main (String[] args) throws java.lang.Exception
{
// works just fine - string has 5 characters and its length is 5
char[] word = {'h', 'e', 'l', 'l', 'o'};
String sWord = new String(word);
System.out.println("Length of '" + sWord + "' is " + sWord.length());
// string appears empty in console, yet its length is 5?
char[] anotherWord = new char[5];
String sAnotherWord = new String(anotherWord);
System.out.println("Length of '" + sAnotherWord + "' is " + sAnotherWord.length());
// isEmpty() even says the blank string is not empty
System.out.println("'" + sAnotherWord + "'" + " is empty: " + sAnotherWord.isEmpty());
}
}
控制台输出:
Length of 'hello' is 5
Length of '' is 5
'' is empty: false
如何创建一个字符数组,其中在字符串末尾任何空白字符留出一个字符串?
String sAnotherWord =(new String(anotherWord))。trim(); – user681574