How do I delete specific characters from a particular String in Java?

Slavisa Perisic picture Slavisa Perisic · Dec 26, 2009 · Viewed 134.9k times · Source

For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).

What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.

Answer

Mark Byers picture Mark Byers · Dec 26, 2009

Reassign the variable to a substring:

s = s.substring(0, s.length() - 1)

Also an alternative way of solving your problem: you might also want to consider using a StringTokenizer to read the file and set the delimiters to be the characters you don't want to be part of words.