我遇到了在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
如何从字符数组中创建字符串,其中字符串末尾的任何空白字符都被省略?
答案 0 :(得分:3)
使用String.trim()尝试trimming
String
中的尾随空格。只是做: -
char[] anotherWord = new char[5];
String sAnotherWord = new String(anotherWord);
sAnotherWord = sAnotherWord.trim();
现在,空格将被移除。
修改1 :正如spencer.sm在其回答中提到的那样,您的第二次打印语句错误,因为它打印sWord.length()
而不是{ {1}}。
答案 1 :(得分:2)
Java中不能有空char
。所有字符必须是一个字符。如果要删除字符串末尾的空格,请使用字符串trim()
方法。
此外,您的第二个打印声明应以sAnotherWord.length()
而不是sWord.length()
结尾。见下文:
System.out.println("Length of '" + sAnotherWord + "' is " + sAnotherWord.length());