[英]Converting a Character Array to a String without Empty Spaces
I'm having an issue with converting an array of characters to a string in Java. 我在用Java将字符数组转换为字符串时遇到问题。 I only want to copy characters that are not empty. 我只想复制不为空的字符。 Take this code for example: 以下面的代码为例:
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());
}
}
Console output: 控制台输出:
Length of 'hello' is 5
Length of '' is 5
'' is empty: false
How do I create a string from an array of characters where any blank characters at the end of the string are left out? 如何从一个字符数组创建一个字符串,而该字符串末尾的空白字符被排除在外?
Try trimming
the trailing spaces in the String
using String.trim() . 尝试使用String.trim() trimming
String
的尾随空格。 Just do : - 做就是了 : -
char[] anotherWord = new char[5];
String sAnotherWord = new String(anotherWord);
sAnotherWord = sAnotherWord.trim();
Now, the spaces would be removed. 现在, 空格将被删除。
Edit 1 : As mention by spencer.sm in his answer, your second print statement is faulty, as it prints sWord.length()
instead of sAnotherWord.length()
. 编辑1 :正如spencer.sm在他的回答中提到的那样 ,您的第二个打印语句有问题,因为它打印的是sWord.length()
而不是sAnotherWord.length()
。
You cannot have an empty char
in Java. Java中不能有空char
。 All chars must be exactly one character. 所有字符必须完全是一个字符。 If you want to remove whitespace at the end of a string, use the String trim()
method. 如果要删除字符串末尾的空格 ,请使用String trim()
方法。
Also, your second print statement should end with sAnotherWord.length()
instead of sWord.length()
. 此外,第二个打印语句应以sAnotherWord.length()
而不是sWord.length()
。 See below: 见下文:
System.out.println("Length of '" + sAnotherWord + "' is " + sAnotherWord.length());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.