Home > Net >  How do I remove the whitespace after each comma in an ArrayList?
How do I remove the whitespace after each comma in an ArrayList?

Time:01-06

I am struggling with removing spaces in an arraylist of strings.

Say the user input is as follows: "I walked my dog", my code outputs this:

[I, walked, my, dog]

I want it to have no spaces as such:

[I,walked,my,dog]

I tried to remove whitespace on each individual string before I add it to the arrayList, but the output still has the spaces.

Scanner input = new Scanner(System.in);
    ArrayList<String> userWords = new ArrayList<String>();
    ArrayList<String> SplituserWords = new ArrayList<String>();
    System.out.println("Please enter your phrase: ");
    userWords.add(input.nextLine());
    
    for (int index = 0; index < userWords.size(); index  ) {
      String[] split = userWords.get(index).split("\\s ");
      for (String word : split) {
        word.replaceAll("\\s ","");
        SplituserWords.add(word);
      }
      System.out.println(SplituserWords);

CodePudding user response:

I suggest just taking advantage of the built-in Arrays#toString() method here:

String words = input.nextLine();
String output = Arrays.toString(words.split(" ")).replace(" ", "");
System.out.println(output);  // [I,walked,my,dog]

CodePudding user response:

When you are writing System.out.println(SplituserWords);, you are implicitly calling ArrayList#toString() which generates the list's string and that includes spaces after commas.

You can instead generates your own string output, for example with:

System.out.println("["   String.join(",", SplituserWords)   "]");
  • Related