Home > Mobile >  Java ArrayList - Replace a specific letter or character within an ArrayList of Strings?
Java ArrayList - Replace a specific letter or character within an ArrayList of Strings?

Time:04-08

I'm trying to replace/remove certain characters within a String ArrayList. Here is the code that I've already tried:

for (int i = 0; i < newList.size(); i  ) {
            if (newList.get(i).contains(".")) {
                newList.get(i).replace(".", "");
            }
        }

I tried iterating through the ArrayList and, if any of the elements contained a ".", then to replace that with emptiness. For example, if one of the words in my ArrayList was "Works.", then the resulted output would be "Works". Unfortunately, this code segment does not seem to be functioning. I did something similar to remove any elements which contains numbers and it worked fine, however I'm not sure if there's specific syntax or methods that needs to be used when replacing just a single character in a String while still keeping the ArrayList element.

CodePudding user response:

newList.get(i).replace(".", "");

This doesn't update the list element - you construct the replaced string, but then discard that string.

You could use set:

newList.set(i, newList.get(i).replace(".", ""));

Or you could use a ListIterator:

ListIterator<String> it = newList.listIterator();
while (it.hasNext()) {
  String s = it.next();
  if (s.contains(".")) {
    it.set(s.replace(".", ""));
  }
}

but a better way would be to use replaceAll, with no need to loop explicitly:

newList.replaceAll(s -> s.replace(".", ""));

There's no need to check contains either: replace won't do anything if the search string is not present.

  • Related