How to split a Java String into an Array and print the resulting Array contents without the Delimiter

684 views Asked by At

I am generating a StringBuilder from an SQL query result set:

StringBuilder sb = new StringBuilder();
PreparedStatement ps1 = null;
String[] systems = null;

try {
    ps1 = c.prepareStatement(systemNames);
    ResultSet rs = ps1.executeQuery();
    while (rs.next()) {
        sb.append(rs.getString("system_name") + ",");
        System.out.println(">-------------------->>> " + sb.toString());
    }
    systems = sb.toString().split(",");
} catch (SQLException e) {
    log.error(e.toString(), e);
} finally {
    if (ps1 != null) {
        try {
            ps1.close();
        } catch (Exception e) {
        }
    }
    if (c != null) {
        try {
            c.close();
        } catch (Exception e) {
        }
    }
}
System.out.println(">-------------------->>> " + systems.toString());

What I am confused about is the string object it prints after the split, the first print statement prints:

>-------------------->>> ACTIVE_DIRECTORY,

While the second, after the delimeter split:

>-------------------->>> [Ljava.lang.String;@387f6ec7

How do I print just ACTIVE_DIECTORY without the comma after the split?

3

There are 3 answers

0
Blake Yarbrough On BEST ANSWER

Be sure to check out the oracle documentation on the Arrays utility class method Arrays.toString(Object[] o). This will 'pretty-print' the contents of your array, rather than the memory address.

Also, the last element will have a comma at the end every time, because you are appending it. To solve this you could do:

myString = myString.replaceAll(",", "");

or

myString[myString.length - 1] = myString[myString.length - 1].replaceAll(",", "");

Depending on whether you want to remove the commas before or after the split(","); Doing this on the last element will take the comma out of the String. I recommend after, because doing it before will make your split not work!

Alternately you could do a replaceAll(",", " "); and then split(" "); but then you might as well just append spaces instead of commas to begin with.

4
Roel Strolenberg On

try replacing:

System.out.println(">-------------------->>> " systems.toString());

with

System.out.println(">-------------------->>> " systems[0]);

since String[] systems is an array of an object, it prints the hash.

1
Shelltux On

It prints out the comma because you appended it. Just print out your array (system var):

Arrays.toString(systems);