java - 将字符数组转换为不带空格的字符串

标签 java arrays string

我在将字符数组转换为 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.trim() 修剪 String 中的尾随空格.只是做:-

char[] anotherWord = new char[5];
String sAnotherWord = new String(anotherWord);
sAnotherWord = sAnotherWord.trim();

现在,空格 将被删除。

编辑 1:如 spencer.sm 所述在他的回答中,您的 second print 语句是错误的,因为它打印的是 sWord.length() 而不是 sAnotherWord.length()

关于java - 将字符数组转换为不带空格的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42870941/

相关文章:

python - Python 中的 Urlencode 西里尔字符

java - 如何为 : '2.0.0-alpha1' in Spring boot 版本启用登录 org.slf4j

C 初学者 - 数组和指针

sql - 用逗号将一个字符串拆分为多列

string - 如何从 Lua NodeMCU 中的日期和时间字符串创建日期对象?

javascript - 从文件中读取 Int 值,全部在一行中

java - 如何在 AlertDialog.builder 中使用 Spinner?

java - 如何设计动态java程序

java - "vm thread"在 JDK 1.6 中的作用是什么

javascript - 在具有随机起始索引的数组中选择 4 个值