如何从此数组创建新数组
String[] data = {"day: monday, color: green", "day: sunday, color: blue", "day: thursday, color: red"};
看起来像这样:
String[] data = {"green", "blue", "red"};
答案 0 :(得分:3)
首先,创建相同大小的新数组:
String[] colors = new String[data.length];
然后遍历源数组解析每个值并将其放入结果中。有很多方法可以解析你的字符串。这取决于解析应该有多强。这是最简单的方法:
for (int i = 0; i < data.length; i++) {
String[] d = data[i].split(" ");
colors[i] = d[d.length - 1];
}
没有更多评论。尝试自己理解代码。这真是微不足道。
答案 1 :(得分:0)
我同意AlexR所说的关于为自己搞清楚的事情。这是使用substring()方法设想for循环和解析操作的另一种方法。同样,请务必预先分配一个String数组以保存结果,即:
String[] result = new String[data.length];
for(int i = 0; i < data.length; i++){
// gets the substring starting on the 5th character
String color = data[i].substring(5);
// adds String to result
result[i] = color;
}