Is there a simple way of converting an ArrayList that contains only characters into a string? So say we have
ArrayList<Character> arrayListChar = new ArrayList<Character>();
arrayListChar.add(a);
arrayListChar.add(b);
arrayListChar.add(c);
So the array list contains a, b, and c. Ideally what I'd want to do is turn that into a String "abc".
Iterator<Character> it = arrayListChar.iterator();
StringBuilder sb = new StringBuilder();
while(it.hasNext()) {
sb.append(it.next());
}
System.out.println(sb.toString());
You could use Apache Common Lang's StringUtils class. It has a join()
function like you find in PHP.
Then the code:
StringUtils.join(arrayListChar, "")
would generate:
abc
int size = list.size();
char[] chars = new char[size];
for (int i = 0; i < size; i++) {
if (list.size() != size) {
throw new ConcurrentModificationException();
}
chars[i] = list.get(i);
}
String s = new String(chars);
Using regex magic:
String result = list.toString().replaceAll(", |\\[|\\]", "");
Get the String representation of the list, which is
[a, b, c]
and then remove the strings "[", "]", and ", "
.
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