Why does Arrays.toString (values) .trim () create [text in square brackets]?

Map<String, String[]> map = request.getParameterMap();
for (Entry<String, String[]> entry : map.entrySet())
{
    String name = entry.getKey();
    String[] values = entry.getValue();
    String valuesStr = Arrays.toString(values).trim();
    LOGGER.warn(valuesStr);

I am trying to see the value of a query parameter using the code above.

Why Arrays.toString(values).trim();will copy the parameter value so that it looks like this:

[Georgio]

What is the best way to get a string without parentheses?

If I do this:

String valuesStr = values[0].trim();

it seems that there is a risk of losing subsequent values ​​in the array.

+3
source share
5 answers

This is just the default formatting used by the method Arrays.toString(Object[]). If you want to skip brackets, you can build the string yourself, for example:

public static String toString(Object[] values)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < values.length; i++)
    {
        if (i != 0)
            sb.append(", ");
        sb.append(values[i].toString());
    }
    return sb.toString();
}
+8
source

- , ( - ) Guava Joiner:

String valuesStr = Joiner.on(",").join(values)

+5

Java toString . , , , , toString, , "[" "] .

+1

, Arrays.toString(Object[]), , Sun JVM. , - [foo, bar, baz].

? . foo, bar, baz? , .

+1

I would suggest you use a line builder or guava, but if you want a quick fix, you can try the following:

Arrays.toString(values).split("[\\[\\]]")[1];

Note. Use the method above only if the values ​​themselves do not contain parentheses.

StringBuilder implementation:

 static String toString(Object ... strings)
 {
    if(strings.length==0)
        return "";
    StringBuilder sb=new StringBuilder();
    int last=strings.length-1;
    for(int i=0;i<last;i++)
        sb.append(strings[i]).append(",");
    sb.append(strings[last]);
    return sb.toString();
 }

UPDATE:

Using substring:

String s=(s=Arrays.toString(arr)).substring(1,s.length()-1); 
+1
source

Source: https://habr.com/ru/post/1769057/


All Articles