为什么 Arrays.toString(values).trim() 会生成 [括号内的文本]?
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);
我正在尝试使用上面的代码查看请求参数值。
为什么 Arrays.toString(values).trim(); 将参数值括起来,使其看起来像这样:
[Georgio]
在此处获取不带括号的字符串的最佳方式是什么?
如果我这样做:
String valuesStr = values[0].trim();
似乎存在丢失数组中后续值的风险。
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'm trying to look at a request parameter value using the code above.
Why does Arrays.toString(values).trim();
bracket the parameter value so it looks like this:
[Georgio]
What's the best way to get the String here without the brackets?
If I do this:
String valuesStr = values[0].trim();
it seems there is a risk of losing subsequent values in the array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这只是 Arrays.toString(Object[]) 方法应用的默认格式。如果您想跳过括号,您可以自己构建字符串,例如:
That is just the default formatting applied by the
Arrays.toString(Object[])
method. If you want to skip the brackets you can build the string yourself, for example:如果您所需的输出是用逗号(或其他内容)分隔的值列表,
我喜欢 Guava 的 Joiner:
String valueStr = Joiner.on(",").join(values)
If your desired output is a list of values separated by commas (or something else),
I like the approach with Guava's Joiner:
String valuesStr = Joiner.on(",").join(values)
Java Arrays toString 方法的默认实现就是这样。
您可以创建一个扩展它的类,专门用于您想要的内容,并覆盖 toString 方法以使其生成您喜欢的字符串,而无需“[”“]”,并具有您喜欢和需要的其他限制。
Java's default implementation of the Arrays toString method is like that.
You can create a class that extends it, specialized for what you want, and overwrite the toString method to make it generate a string of your liking, without the "[" "]"s, and with other restrictions of your liking and need.
我相信这就是 Arrays.toString(Object[]) 的实现方式,至少在 Sun JVM 上是这样。如果数组有多个元素,您会看到类似
[foo, bar, baz]
的内容。您是否希望获得基本相同的输出(不带括号)?例如
foo、bar、baz
?如果是这样,那么编写自己的方法应该很容易。I believe this is just how the implementation of
Arrays.toString(Object[])
works, at least on the Sun JVM. If the array had multiple elements, you would see something like[foo, bar, baz]
.Are you looking to basically get the same output, without the brackets? E.g.
foo, bar, baz
? If so, then it should be pretty easy to write your own method.我建议您使用字符串生成器或番石榴的连接器,但如果您想要快速修复,您可以尝试以下操作:
注意:仅当值本身不包含括号时才使用上述方法。
StringBuilder实现:
更新:
使用子字符串:
I would suggest you use a string-builder or guava's joiner but if you want a quick fix,you can try this:
Note: Use the above method only if the values themselves doesn't contain bracket's in them.
StringBuilder Implementaion:
UPDATE:
Using substring: