Search code examples
javastringliststringbuffer

how to add list items to stringbuffer?


I've got a list which contains a string that is split up, i want to add the items from the list to a stringbuffer but im currently failing to do so

Here is my code that i currently got:

 public void AAAAA(String text, int width)
  {
    List<String> items = Arrays.asList(text.split(" "));
    StringBuffer use = new StringBuffer(items);
    use.insert(width, "\n");
    System.out.println(use);
  }

how would i go about adding all my items to the stringbuffer?


Solution

  • To insert a character (newline in your case) into an arbitrary index of a string, you don't need to split the string. Just pass it to a StringBuilder (because StringBuilder allows you to modify its contents, while String does not) and then do the insertion through the insert method.

    Update

    To insert a character into an arbitrary list of words, instead, you need to split the input text, through Arrays.asList as you tried, right; then do the insertion into the list object through the add method. And, at the end, you can serialize the items back to a string iterating the elements and concatenating them out to a StringBuilder using blanks as separators.