Java: how to add text to each array item?
I have a Jav开发者_如何学JAVAa array of strings.
I need to add some text before and after each array element.
e.g. ["first","second",.. "last"]
should become
["<title>first</title>","<author>second</author>" ...]
and so on. Should I use a for statement ?
thanks
I would solve by doing something like this:
public class Test {
public static void main(String[] args) {
String[] strs = { "first", "second", "last" };
String[] tags = { "title", "author", "something" };
for (int i = 0; i < strs.length; i++)
strs[i] = String.format("<%s>%s</%1$s>", tags[i], strs[i]);
String result = "";
for (String str : strs)
result += str;
System.out.println(result);
}
}
Output:
<title>first</title><author>second</author><something>last</something>
精彩评论