我正在尝试将 String builder 转换为 java 中的 String 数组。我使用 to String 方法将 Stringbuilder 转换为 String,然后使用 split 方法将其转换为字符串数组。
我在数组大小方面遇到了一些问题。 String builder 的输出如下:0,,1,,,,,,,,,,2,,,
。实际上它包含 15 个元素,但它显示 stringbuilder 的大小为 18。转换为 String 数组后,它显示的大小为 13。
我是不是用错了方法?是否有其他方法可以将 String builder 转换为 String Array?
StringBuilder output = new StringBuilder();
for (String str : listToSearch) {
int index = findIndex(headerArrayList, str);
if (index > -1) {
output.append(index);
} else {
output.append(str);
}
output.append(",");
}
String out = output.toString();
String[] destIndexArray = out.split(",");
findIndex
方法:
private static int findIndex(List<String> headerList, String element) {
for (int i = 0; i < headerList.size(); i++) {
if (headerList.get(i).equals(element)) {
return i;
}
}
return -1;
}
最佳答案
Am I doing wrong method?
您的代码有很多地方需要改进。我建议一些:
- 与其重新发明轮子,不如寻找现有的 API:https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#indexOf(java.lang.Object)
- 您只能添加
String
s 而不是索引。
for (String str :listToSearch) {
int index=headerArrayList.indexOf(str);
if (index < 0) {
output.append(str);
output.append(",");
}
// if(!headerArrayList.contains(str))
// output.append(str);
// output.append(",");
}
- 使用
List<String>
而不是StringBuilder
.
Is there is other method to convert String builder to String Array?
是的,但是如果你遵循以上几点,你就不需要它了。但既然你问了。看到这个:How can a StringBuilder best be converted to a String[]?
关于java - 字符串生成器到 java 中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41327094/