0

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.

1
  • 1
    remember that a String is immutable - so it cannot be changed - so replace() must return a new (modified) String, which is not being used in your code Commented Apr 7, 2022 at 17:48

1 Answer 1

1
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.