2017-03-18 204 views
1

我在將字符數組轉換爲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

String sAnotherWord =(new String(anotherWord))。trim(); – user681574

回答

3

嘗試trimmingString的尾部空格使用String.trim()。只要做到: -

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

現在,空間將被刪除。

編輯1:由於spencer.sm在他的回答,何況你秒打印說法是錯誤的,因爲它打印sWord.length(),而不是sAnotherWord.length()

2

在Java中不能有空的char。所有的字符都必須是一個字符。如果要在字符串末尾刪除空格,請使用字符串trim()方法。


而且,你的第二個print語句應該sAnotherWord.length()而不是sWord.length()結束。如下所示:

System.out.println("Length of '" + sAnotherWord + "' is " + sAnotherWord.length()); 
+0

謝謝!我修正了錯字。 – zbalda

+0

爲什麼downvote? –