I am trying to convert String builder to String array in java.I have used to String method to convert the Stringbuilder to String and then use split method to convert it to String array.
I am facing some issue in array size. The output of String builder is as follows: 0,,1,,,,,,,,,,2,,,
. Actually it contains 15 elements, but it's showing the size of stringbuilder as 18. And after converting to String array, it's showing size as 13.
Am I doing wrong method? Is there is other method to convert String builder to 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(",");
The findIndex
method:
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?
There are many places your code need improvements. I'm suggesting some:
String
s instead of index.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>
instead of StringBuilder
.Is there is other method to convert String builder to String Array?
Yes, but if you follow above points, you won't need it. but since you asked. See this: How can a StringBuilder best be converted to a String[]?
See using stringbuilder and again manipulating it and converting it into array is not a good idea. Instead insert everything into list of string, and to check if string is integer or not use this :
str.matches("^-?\\d+$");
And if you want to convert it into array you can do that
String[] str = list.toArray(new String[list.size()])
Have you simply tried in it with one line code
stringBuilder.toString.split("delimiter")
?
Which is in your case, might look like
destIndexArray = output.toString.split(",")
If that doesnt work, then instead of converting into a StringBuilder, you can do this
List<String> output = new List<String>();
for (String str : listToSearch) {
int index = findIndex(headerArrayList, str);
if (index > -1) {
output.add(index);
} else {
output.add(str);
}
}
I think in this case you can do whatever with your list, no need of delimiter. Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With