1

I'm having an issue with converting an array of characters to a string in 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?

1
  • String sAnotherWord = (new String(anotherWord)).trim(); Commented Mar 18, 2017 at 5:46

2 Answers 2

3

Try trimming the trailing spaces in the String using String.trim(). 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().

Sign up to request clarification or add additional context in comments.

Comments

2

You cannot have an empty char in Java. All chars must be exactly one character. If you want to remove whitespace at the end of a string, use the String trim() method.


Also, your second print statement should end with sAnotherWord.length() instead of sWord.length(). See below:

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

1 Comment

Thanks! I fixed the typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.